rel_3_0 moved to HEAD
authortipaul <tipaul>
Fri, 9 Mar 2007 15:12:54 +0000 (15:12 +0000)
committertipaul <tipaul>
Fri, 9 Mar 2007 15:12:54 +0000 (15:12 +0000)
81 files changed:
opac/changelanguage.pl
opac/opac-ISBDdetail.pl
opac/opac-MARCdetail.pl
opac/opac-account.pl
opac/opac-addbookbybiblionumber.pl
opac/opac-alert-subscribe.pl
opac/opac-basket.pl
opac/opac-detail.pl
opac/opac-detailprint.pl
opac/opac-dictionary.pl
opac/opac-logout.pl
opac/opac-main.pl
opac/opac-passwd.pl
opac/opac-readingrecord.pl
opac/opac-renew.pl
opac/opac-reserve.pl
opac/opac-review.pl
opac/opac-search.pl
opac/opac-sendbasket.pl
opac/opac-serial-issues.pl
opac/opac-shelves.pl
opac/opac-showreviews.pl
opac/opac-suggestions.pl
opac/opac-user.pl
opac/opac-userdetails.pl
opac/opac-userupdate.pl
reports/acquisitions_stats.pl
reports/bor_issues_top.pl
reports/borrowers_out.pl
reports/borrowers_stats.pl
reports/cat_issues_top.pl
reports/catalogue_out.pl
reports/catalogue_stats.pl
reports/inventory.pl
reports/issues_avg_stats.pl
reports/issues_by_borrower_category.plugin
reports/issues_stats.pl
reports/itemtypes.plugin
reports/manager.pl
reports/reports-home.pl
reports/reservereport.pl
reports/stats.print.pl
reports/stats.screen.pl
reserve/modrequest.pl
reserve/placerequest.pl
reserve/request.pl
rss/lastAcquired-1.0.tmpl
rss/lastAcquired-2.0.tmpl
rss/lastAcquired.tmpl
rss/rss.pl
serials/acqui-search-result.pl
serials/acqui-search.pl
serials/claims.pl
serials/distributedto.pl
serials/lateissues-excel.pl
serials/member-search.pl
serials/reorder_members.pl
serials/routing-preview.pl
serials/routing.pl
serials/serial-issues.pl
serials/serials-home.pl
serials/subscription-add.pl
serials/subscription-bib-search.pl
serials/subscription-copy.pl
serials/subscription-detail.pl
serials/subscription-renew.pl
serials/viewalerts.pl
suggestion/acceptorreject.pl
tools/barcodes.pl
tools/barcodesGenerator.pl
tools/exceptionHolidays.pl
tools/export.pl
tools/holidays.pl
tools/import.pl
tools/koha-news.pl
tools/letter.pl
tools/newHolidays.pl
tools/overduerules.pl
tools/printerConfig.pl
tools/tools-home.pl
updater/updatedatabase

index ad616a7..4ab3d3b 100755 (executable)
@@ -1,10 +1,25 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use C4::Output;
 use CGI;
 
-my $query=new CGI;
-my $language=$query->param('language');
-my $url=$query->referer();
+my $query    = new CGI;
+my $language = $query->param('language');
+my $url      = $query->referer();
 
-setlanguagecookie($query,$language,$url);
+setlanguagecookie( $query, $language, $url );
index 11eff60..77094fb 100755 (executable)
 
 =head1 NAME
 
-MARCdetail.pl : script to show a biblio in MARC format
+opac-ISBDdetail.pl : script to show a biblio in ISBD format
 
 
 =head1 DESCRIPTION
 
-This script needs a biblionumber in bib parameter (bibnumber
-from koha style DB.  Automaticaly maps to marc biblionumber).
+This script needs a biblionumber as parameter 
 
-It shows the biblio in a (nice) MARC format depending on MARC
-parameters tables.
+It shows the biblio
 
-The template is in <templates_dir>/catalogue/MARCdetail.tmpl.
+The template is in <templates_dir>/catalogue/ISBDdetail.tmpl.
 this template must be divided into 11 "tabs".
 
 The first 10 tabs present the biblio, the 11th one presents
@@ -44,7 +42,6 @@ the items attached to the biblio
 
 =cut
 
-
 use strict;
 require Exporter;
 use C4::Auth;
@@ -52,135 +49,183 @@ use C4::Context;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use CGI;
-use C4::Search;
 use MARC::Record;
 use C4::Biblio;
 use C4::Acquisition;
-use C4::Serials; #uses getsubscriptionfrom biblionumber
-use HTML::Template;
+use C4::Review;
+use C4::Serials;    # uses getsubscriptionfrom biblionumber
+use C4::Koha;       # use getitemtypeinfo
+use C4::Members;    # GetMember
 
-my $query=new CGI;
+my $query = new CGI;
 
-my $dbh=C4::Context->dbh;
+my $dbh = C4::Context->dbh;
 
-my $biblionumber=$query->param('bib');
-my $bibid = $query->param('bibid');
-$bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$biblionumber) unless $bibid;
-$biblionumber = &MARCfind_oldbiblionumber_from_MARCbibid($dbh,$bibid) unless $biblionumber;
-my $itemtype = &MARCfind_frameworkcode($dbh,$bibid);
-my $tagslib = &MARCgettagslib($dbh,1,$itemtype);
+my $biblionumber = $query->param('biblionumber');
+my $itemtype     = &MARCfind_frameworkcode($biblionumber);
+my $tagslib      = &MARCgettagslib( $dbh, 1, $itemtype );
 
-my $record =MARCgetbiblio($dbh,$bibid);
+my $record = GetMarcBiblio($biblionumber);
 
 #coping with subscriptions
 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
-my $dat = MARCmarc2koha($dbh,$record);
-my @subscriptions = GetSubscriptions($dat->{title},$dat->{issn},$biblionumber);
+my $dat                 = MARCmarc2koha( $dbh, $record );
+my @subscriptions       =
+  GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
 my @subs;
-foreach my $subscription (@subscriptions){
-       my %cell;
-       $cell{subscriptionid}= $subscription->{subscriptionid};
-       $cell{subscriptionnotes}= $subscription->{notes};
-       #get the three latest serials.
-       $cell{latestserials}=GetLatestSerials($subscription->{subscriptionid},3);
-       push @subs, \%cell;
+foreach my $subscription (@subscriptions) {
+    my %cell;
+    $cell{subscriptionid}    = $subscription->{subscriptionid};
+    $cell{subscriptionnotes} = $subscription->{notes};
+
+    #get the three latest serials.
+    $cell{latestserials} =
+      GetLatestSerials( $subscription->{subscriptionid}, 3 );
+    push @subs, \%cell;
 }
 
 # open template
-my ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-ISBDdetail.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            debug => 1,
-                            });
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-ISBDdetail.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+        debug           => 1,
+    }
+);
 $template->param(
-                               subscriptions => \@subs,
-                               subscriptionsnumber => $subscriptionsnumber,
+    subscriptions       => \@subs,
+    subscriptionsnumber => $subscriptionsnumber,
 );
 
 my $ISBD = C4::Context->preference('ISBD');
+
 # my @blocs = split /\@/,$ISBD;
 # my @fields = $record->fields();
 my $res;
+
 # foreach my $bloc (@blocs) {
-#      $bloc =~ s/\n//g;
-       my $bloc = $ISBD;
-       my $blocres;
-       foreach my $isbdfield (split /#/,$bloc) {
-#              $isbdfield= /(.?.?.?)/;
-               $isbdfield =~ /(\d\d\d)\|(.*)\|(.*)\|(.*)/;
-               my $fieldvalue=$1;
-               my $textbefore=$2;
-               my $analysestring=$3;
-               my $textafter=$4;
-#              warn "==> $1 / $2 / $3 / $4";
-#              my $fieldvalue=substr($isbdfield,0,3);
-               if ($fieldvalue>0) {
-       #               warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
-#                      warn "FV : $fieldvalue";
-                       my $hasputtextbefore=0;
-                       foreach my $field ($record->field($fieldvalue)) {
-                               my $calculated = $analysestring;
-                               my $tag = $field->tag();
-                               if ($tag<10) {
-                               } else {
-                                       my @subf = $field->subfields;
-                                       for my $i (0..$#subf) {
-                                               my $subfieldcode = $subf[$i][0];
-                                               my $subfieldvalue = get_authorised_value_desc($tag, $subf[$i][0], $subf[$i][1], '', $dbh);
-                                               my $tagsubf = $tag.$subfieldcode;
-                                               $calculated =~ s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
-                                       }
-                                       # field builded, store the result
-                                       if ($calculated && !$hasputtextbefore) { # put textbefore if not done
-                                               $blocres .=$textbefore;
-                                               $hasputtextbefore=1
-                                       }
-                                       # remove punctuation at start
-                                       $calculated =~ s/^( |;|:|\.|-)*//g;
-                                       $blocres.=$calculated;
-                               }
-                       }
-                       $blocres .=$textafter if $hasputtextbefore;
-               } else {
-                       $blocres.=$isbdfield;
-               }
-       }
-       $res.=$blocres;
+#     $bloc =~ s/\n//g;
+my $bloc = $ISBD;
+my $blocres;
+foreach my $isbdfield ( split /#/, $bloc ) {
+
+    #         $isbdfield= /(.?.?.?)/;
+    $isbdfield =~ /(\d\d\d)\|(.*)\|(.*)\|(.*)/;
+    my $fieldvalue    = $1;
+    my $textbefore    = $2;
+    my $analysestring = $3;
+    my $textafter     = $4;
+
+    #         warn "==> $1 / $2 / $3 / $4";
+    #         my $fieldvalue=substr($isbdfield,0,3);
+    if ( $fieldvalue > 0 ) {
+
+        #         warn "ERROR IN ISBD DEFINITION at : $isbdfield" unless $fieldvalue;
+        #             warn "FV : $fieldvalue";
+        my $hasputtextbefore = 0;
+        foreach my $field ( $record->field($fieldvalue) ) {
+            my $calculated = $analysestring;
+            my $tag        = $field->tag();
+            if ( $tag < 10 ) {
+            }
+            else {
+                my @subf = $field->subfields;
+                for my $i ( 0 .. $#subf ) {
+                    my $subfieldcode  = $subf[$i][0];
+                    my $subfieldvalue =
+                      GetAuthorisedValueDesc( $tag, $subf[$i][0],
+                        $subf[$i][1], '', $tagslib );
+                    my $tagsubf = $tag . $subfieldcode;
+                    $calculated =~
+s/\{(.?.?.?.?)$tagsubf(.*?)\}/$1$subfieldvalue$2\{$1$tagsubf$2\}/g;
+                }
+
+                # field builded, store the result
+                if ( $calculated && !$hasputtextbefore )
+                {    # put textbefore if not done
+                    $blocres .= $textbefore;
+                    $hasputtextbefore = 1;
+                }
+
+                # remove punctuation at start
+                $calculated =~ s/^( |;|:|\.|-)*//g;
+                $blocres .= $calculated;
+            }
+        }
+        $blocres .= $textafter if $hasputtextbefore;
+    }
+    else {
+        $blocres .= $isbdfield;
+    }
+}
+$res .= $blocres;
+
 # }
 $res =~ s/\{(.*?)\}//g;
 $res =~ s/\\n/\n/g;
 $res =~ s/\n/<br\/>/g;
+
 # remove empty ()
 $res =~ s/\(\)//g;
-$template->param(ISBD => $res,
-                               biblionumber => $biblionumber);
 
-output_html_with_http_headers $query, $cookie, $template->output;
+my $reviews = getreviews( $biblionumber, 1 );
+foreach ( @$reviews ) {
+    my $borrower_number_review = $_->{borrowernumber};
+    my $borrowerData           = GetMember('',$borrower_number_review);
+    # setting some borrower info into this hash
+    $_->{title}     = $borrowerData->{'title'};
+    $_->{surname}   = $borrowerData->{'surname'};
+    $_->{firstname} = $borrowerData->{'firstname'};
+}
 
-sub get_authorised_value_desc ($$$$$) {
-   my($tag, $subfield, $value, $framework, $dbh) = @_;
 
-   #---- branch
-    if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
-       return getbranchname($value);
-    }
+$template->param(
+    ISBD         => $res,
+    biblionumber => $biblionumber,
+    reviews             => $reviews,
+);
+
+## Amazon.com stuff
+#not used unless preference set
+if ( C4::Context->preference("AmazonContent") == 1 ) {
+    use C4::Amazon;
+    $dat->{'amazonisbn'} = $dat->{'isbn'};
+    $dat->{'amazonisbn'} =~ s|-||g;
 
-   #---- itemtypes
-   if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
-       return ItemType($value);
+    $template->param( amazonisbn => $dat->{amazonisbn} );
+
+    my $amazon_details = &get_amazon_details( $dat->{amazonisbn} );
+
+    foreach my $result ( @{ $amazon_details->{Details} } ) {
+        $template->param( item_description => $result->{ProductDescription} );
+        $template->param( image            => $result->{ImageUrlMedium} );
+        $template->param( list_price       => $result->{ListPrice} );
+        $template->param( amazon_url       => $result->{url} );
     }
 
-   #---- "true" authorized value
-   my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
-
-   if ($category ne "") {
-       my $sth = $dbh->prepare("select lib from authorised_values where category = ? and authorised_value = ?");
-       $sth->execute($category, $value);
-       my $data = $sth->fetchrow_hashref;
-       return $data->{'lib'};
-   } else {
-       return $value; # if nothing is found return the original value
-   }
+    my @products;
+    my @reviews;
+    for my $details ( @{ $amazon_details->{Details} } ) {
+        next unless $details->{SimilarProducts};
+        for my $product ( @{ $details->{SimilarProducts}->{Product} } ) {
+            push @products, +{ Product => $product };
+        }
+        next unless $details->{Reviews};
+        for my $product ( @{ $details->{Reviews}->{AvgCustomerRating} } ) {
+            $template->param( rating => $product * 20 );
+        }
+        for my $reviews ( @{ $details->{Reviews}->{CustomerReview} } ) {
+            push @reviews,
+              +{
+                Summary => $reviews->{Summary},
+                Comment => $reviews->{Comment},
+              };
+        }
+    }
+    $template->param( SIMILAR_PRODUCTS => \@products );
+    $template->param( AMAZONREVIEWS    => \@reviews );
 }
+
+output_html_with_http_headers $query, $cookie, $template->output;
index 32e4898..7ab3579 100755 (executable)
@@ -26,8 +26,7 @@ MARCdetail.pl : script to show a biblio in MARC format
 
 =head1 DESCRIPTION
 
-This script needs a biblionumber in bib parameter (bibnumber
-from koha style DB.  Automaticaly maps to marc biblionumber).
+This script needs a biblionumber as  parameter
 
 It shows the biblio in a (nice) MARC format depending on MARC
 parameters tables.
@@ -38,13 +37,8 @@ this template must be divided into 11 "tabs".
 The first 10 tabs present the biblio, the 11th one presents
 the items attached to the biblio
 
-=head1 FUNCTIONS
-
-=over 2
-
 =cut
 
-
 use strict;
 require Exporter;
 use C4::Auth;
@@ -52,196 +46,235 @@ use C4::Context;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use CGI;
-use C4::Search;
 use MARC::Record;
 use C4::Biblio;
 use C4::Acquisition;
-use HTML::Template;
+use C4::Koha;
 
-my $query=new CGI;
+my $query = new CGI;
 
-my $dbh=C4::Context->dbh;
+my $dbh = C4::Context->dbh;
 
-my $biblionumber=$query->param('bib');
-my $bibid = $query->param('bibid');
-$bibid = &MARCfind_MARCbibid_from_oldbiblionumber($dbh,$biblionumber) unless $bibid;
-$biblionumber = &MARCfind_oldbiblionumber_from_MARCbibid($dbh,$bibid) unless $biblionumber;
-my $itemtype = &MARCfind_frameworkcode($dbh,$bibid);
-my $tagslib = &MARCgettagslib($dbh,0,$itemtype);
+my $biblionumber = $query->param('biblionumber');
+my $itemtype     = &MARCfind_frameworkcode($biblionumber);
+my $tagslib      = &MARCgettagslib( $dbh, 0, $itemtype );
+
+my $record = GetMarcBiblio($biblionumber);
 
-my $record =MARCgetbiblio($dbh,$bibid);
 # open template
-my ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-MARCdetail.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            debug => 1,
-                            });
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-MARCdetail.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+        debug           => 1,
+    }
+);
+# adding the $RequestOnOpac param
+my $RequestOnOpac;
+if (C4::Context->preference("RequestOnOpac")) {
+       $RequestOnOpac = 1;
+}
 
 # fill arrays
-my @loop_data =();
+my @loop_data = ();
 my $tag;
+
 # loop through each tab 0 through 9
-for (my $tabloop = 0; $tabloop<=10;$tabloop++) {
-# loop through each tag
-       my @loop_data =();
-       my @subfields_data;
-       # deal with leader
-       unless ($tagslib->{'000'}->{'@'}->{tab}  ne $tabloop  or $tagslib->{'000'}->{'@'}->{hidden}>0) {
-               my %subfield_data;
-               $subfield_data{marc_lib}=$tagslib->{'000'}->{'@'}->{lib};
-               $subfield_data{marc_value}=$record->leader();
-               $subfield_data{marc_subfield}='@';
-               $subfield_data{marc_tag}='000';
-               push(@subfields_data, \%subfield_data);
-               my %tag_data;
-                       $tag_data{tag}='000 -'. $tagslib->{'000'}->{lib};
-               my @tmp = @subfields_data;
-               $tag_data{subfield} = \@tmp;
-               push (@loop_data, \%tag_data);
-               undef @subfields_data;
-       }
-       my @fields = $record->fields();
-       for (my $x_i=0;$x_i<=$#fields;$x_i++) {
-               # if tag <10, there's no subfield, use the "@" trick
-               if ($fields[$x_i]->tag()<10) {
-                       next if ($tagslib->{$fields[$x_i]->tag()}->{'@'}->{tab}  ne $tabloop);
-                       next if ($tagslib->{$fields[$x_i]->tag()}->{'@'}->{hidden}>0);
-                       my %subfield_data;
-                       $subfield_data{marc_lib}=$tagslib->{$fields[$x_i]->tag()}->{'@'}->{lib};
-                       $subfield_data{marc_value}=$fields[$x_i]->data();
-                       $subfield_data{marc_subfield}='@';
-                       $subfield_data{marc_tag}=$fields[$x_i]->tag();
-                       push(@subfields_data, \%subfield_data);
-               } else {
-                       my @subf=$fields[$x_i]->subfields;
-       # loop through each subfield
-                       for my $i (0..$#subf) {
-                               $subf[$i][0] = "@" unless $subf[$i][0];
-                               next if ($tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{tab}  ne $tabloop);
-                               next if ($tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{hidden}>0);
-                               my %subfield_data;
-                               $subfield_data{marc_lib}=$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{lib};
-                               $subfield_data{link}=$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{link};
-                               $subf[$i][1] =~ s/\n/<br\/>/g;
-                               if ($tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{isurl}) {
-                                       $subfield_data{marc_value}="<a href=\"$subf[$i][1]\">$subf[$i][1]</a>";
-                               } elsif ($tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{kohafield} eq "biblioitems.isbn") {
-#                                      warn " tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}. "ISBN : ".$subf[$i][1]."PosttraitementISBN :".DisplayISBN($subf[$i][1]);
-                                       $subfield_data{marc_value}=DisplayISBN($subf[$i][1]);
-                               } else {
-                                       if ($tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}->{authtypecode}) {
-                                               $subfield_data{authority}=$fields[$x_i]->subfield(9);
-                                       }
-                                       $subfield_data{marc_value}=get_authorised_value_desc($fields[$x_i]->tag(), $subf[$i][0], $subf[$i][1], '', $dbh);
-                               }
-                               $subfield_data{marc_subfield}=$subf[$i][0];
-                               $subfield_data{marc_tag}=$fields[$x_i]->tag();
-                               push(@subfields_data, \%subfield_data);
-                       }
-               }
-               if ($#subfields_data>=0) {
-                       my %tag_data;
-                       if (($fields[$x_i]->tag() eq $fields[$x_i-1]->tag()) && (C4::Context->preference('LabelMARCView') eq 'economical')) {
-                               $tag_data{tag}="";
-                       } else {
-                               if (C4::Context->preference('hide_marc')) {
-                                       $tag_data{tag}=$tagslib->{$fields[$x_i]->tag()}->{lib};
-                               } else {
-                                       $tag_data{tag}=$fields[$x_i]->tag().' -'. $tagslib->{$fields[$x_i]->tag()}->{lib};
-                               }
-                       }
-                       my @tmp = @subfields_data;
-                       $tag_data{subfield} = \@tmp;
-                       push (@loop_data, \%tag_data);
-                       undef @subfields_data;
-               }
-       }
-       $template->param($tabloop."XX" =>\@loop_data);
+for ( my $tabloop = 0 ; $tabloop <= 10 ; $tabloop++ ) {
+
+    # loop through each tag
+    my @loop_data = ();
+    my @subfields_data;
+
+    # deal with leader
+    unless ( $tagslib->{'000'}->{'@'}->{tab} ne $tabloop
+        or $tagslib->{'000'}->{'@'}->{hidden} > 0 )
+    {
+        my %subfield_data;
+        $subfield_data{marc_lib}      = $tagslib->{'000'}->{'@'}->{lib};
+        $subfield_data{marc_value}    = $record->leader();
+        $subfield_data{marc_subfield} = '@';
+        $subfield_data{marc_tag}      = '000';
+        push( @subfields_data, \%subfield_data );
+        my %tag_data;
+        $tag_data{tag} = '000 -' . $tagslib->{'000'}->{lib};
+        my @tmp = @subfields_data;
+        $tag_data{subfield} = \@tmp;
+        push( @loop_data, \%tag_data );
+        undef @subfields_data;
+    }
+    my @fields = $record->fields();
+    for ( my $x_i = 0 ; $x_i <= $#fields ; $x_i++ ) {
+
+        # if tag <10, there's no subfield, use the "@" trick
+        if ( $fields[$x_i]->tag() < 10 ) {
+            next
+              if (
+                $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{tab} ne $tabloop );
+            next if ( $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{hidden} > 0 );
+            my %subfield_data;
+            $subfield_data{marc_lib} =
+              $tagslib->{ $fields[$x_i]->tag() }->{'@'}->{lib};
+            $subfield_data{marc_value}    = $fields[$x_i]->data();
+            $subfield_data{marc_subfield} = '@';
+            $subfield_data{marc_tag}      = $fields[$x_i]->tag();
+            push( @subfields_data, \%subfield_data );
+        }
+        else {
+            my @subf = $fields[$x_i]->subfields;
+
+            # loop through each subfield
+            for my $i ( 0 .. $#subf ) {
+                $subf[$i][0] = "@" unless $subf[$i][0];
+                next
+                  if (
+                    $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{tab}
+                    ne $tabloop );
+                next
+                  if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }
+                    ->{hidden} > 0 );
+                my %subfield_data;
+                $subfield_data{marc_lib} =
+                  $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{lib};
+                $subfield_data{link} =
+                  $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }->{link};
+                $subf[$i][1] =~ s/\n/<br\/>/g;
+                if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }
+                    ->{isurl} )
+                {
+                    $subfield_data{marc_value} =
+                      "<a href=\"$subf[$i][1]\">$subf[$i][1]</a>";
+                }
+                elsif ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }
+                    ->{kohafield} eq "biblioitems.isbn" )
+                {
+
+#                    warn " tag : ".$tagslib->{$fields[$x_i]->tag()}." subfield :".$tagslib->{$fields[$x_i]->tag()}->{$subf[$i][0]}. "ISBN : ".$subf[$i][1]."PosttraitementISBN :".DisplayISBN($subf[$i][1]);
+                    $subfield_data{marc_value} = DisplayISBN( $subf[$i][1] );
+                }
+                else {
+                    if ( $tagslib->{ $fields[$x_i]->tag() }->{ $subf[$i][0] }
+                        ->{authtypecode} )
+                    {
+                        $subfield_data{authority} = $fields[$x_i]->subfield(9);
+                    }
+                    $subfield_data{marc_value} =
+                      GetAuthorisedValueDesc( $fields[$x_i]->tag(),
+                        $subf[$i][0], $subf[$i][1], '', $tagslib );
+                }
+                $subfield_data{marc_subfield} = $subf[$i][0];
+                $subfield_data{marc_tag}      = $fields[$x_i]->tag();
+                push( @subfields_data, \%subfield_data );
+            }
+        }
+        if ( $#subfields_data >= 0 ) {
+            my %tag_data;
+            if (   ( $fields[$x_i]->tag() eq $fields[ $x_i - 1 ]->tag() )
+                && ( C4::Context->preference('LabelMARCView') eq 'economical' )
+              )
+            {
+                $tag_data{tag} = "";
+            }
+            else {
+                if ( C4::Context->preference('hide_marc') ) {
+                    $tag_data{tag} = $tagslib->{ $fields[$x_i]->tag() }->{lib};
+                }
+                else {
+                    $tag_data{tag} =
+                        $fields[$x_i]->tag() . ' -'
+                      . $tagslib->{ $fields[$x_i]->tag() }->{lib};
+                }
+            }
+            my @tmp = @subfields_data;
+            $tag_data{subfield} = \@tmp;
+            push( @loop_data, \%tag_data );
+            undef @subfields_data;
+        }
+    }
+    $template->param( $tabloop . "XX" => \@loop_data );
 }
+
+
 # now, build item tab !
 # the main difference is that datas are in lines and not in columns : thus, we build the <th> first, then the values...
 # loop through each tag
 # warning : we may have differents number of columns in each row. Thus, we first build a hash, complete it if necessary
 # then construct template.
 my @fields = $record->fields();
-my %witness; #---- stores the list of subfields used at least once, with the "meaning" of the code
+my %witness
+  ; #---- stores the list of subfields used at least once, with the "meaning" of the code
 my @big_array;
 foreach my $field (@fields) {
-       next if ($field->tag()<10);
-       my @subf=$field->subfields;
-       my %this_row;
-# loop through each subfield
-       for my $i (0..$#subf) {
-               next if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{tab}  ne 10);
-               $witness{$subf[$i][0]} = $tagslib->{$field->tag()}->{$subf[$i][0]}->{lib};
-        if ($tagslib->{$field->tag()}->{$subf[$i][0]}->{isurl}) {
-            $this_row{$subf[$i][0]}="<a href=\"$subf[$i][1]\">$subf[$i][1]</a>";
-        } elsif ($tagslib->{$field->tag()}->{$subf[$i][0]}->{kohafield} eq "biblioitems.isbn") {
-            $this_row{$subf[$i][0]}=DisplayISBN($subf[$i][1]);
-        } else {
-            $this_row{$subf[$i][0]}=get_authorised_value_desc($field->tag(), $subf[$i][0], $subf[$i][1], '', $dbh);
+    next if ( $field->tag() < 10 );
+    my @subf = $field->subfields;
+    my %this_row;
+
+    # loop through each subfield
+    for my $i ( 0 .. $#subf ) {
+        next if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{tab} ne 10 );
+        $witness{ $subf[$i][0] } =
+          $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{lib};
+        if ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{isurl} ) {
+            $this_row{ $subf[$i][0] } =
+              "<a href=\"$subf[$i][1]\">$subf[$i][1]</a>";
+        }
+        elsif ( $tagslib->{ $field->tag() }->{ $subf[$i][0] }->{kohafield} eq
+            "biblioitems.isbn" )
+        {
+            $this_row{ $subf[$i][0] } = DisplayISBN( $subf[$i][1] );
+        }
+        else {
+            $this_row{ $subf[$i][0] } =
+              GetAuthorisedValueDesc( $field->tag(), $subf[$i][0],
+                $subf[$i][1], '', $tagslib );
         }
-       }
-       if (%this_row) {
-               push(@big_array, \%this_row);
-       }
+    }
+    if (%this_row) {
+        push( @big_array, \%this_row );
+    }
 }
-my ($holdingbrtagf,$holdingbrtagsubf) = &MARCfind_marc_from_kohafield($dbh,"items.holdingbranch",$itemtype);
-@big_array = sort {$a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf}} @big_array;
+my ( $holdingbrtagf, $holdingbrtagsubf ) =
+  &MARCfind_marc_from_kohafield( $dbh, "items.holdingbranch", $itemtype );
+@big_array =
+  sort { $a->{$holdingbrtagsubf} cmp $b->{$holdingbrtagsubf} } @big_array;
+
 #fill big_row with missing datas
-foreach my $subfield_code  (keys(%witness)) {
-       for (my $i=0;$i<=$#big_array;$i++) {
-               $big_array[$i]{$subfield_code}="&nbsp;" unless ($big_array[$i]{$subfield_code});
-       }
+foreach my $subfield_code ( keys(%witness) ) {
+    for ( my $i = 0 ; $i <= $#big_array ; $i++ ) {
+        $big_array[$i]{$subfield_code} = "&nbsp;"
+          unless ( $big_array[$i]{$subfield_code} );
+    }
 }
+
 # now, construct template !
 my @item_value_loop;
 my @header_value_loop;
-for (my $i=0;$i<=$#big_array; $i++) {
-       my $items_data;
-       foreach my $subfield_code (keys(%witness)) {
-               $items_data .="<td>".$big_array[$i]{$subfield_code}."</td>";
-       }
-       my %row_data;
-       $row_data{item_value} = $items_data;
-       push(@item_value_loop,\%row_data);
-}
-foreach my $subfield_code (keys(%witness)) {
-       my %header_value;
-       $header_value{header_value} = $witness{$subfield_code};
-       push(@header_value_loop, \%header_value);
+for ( my $i = 0 ; $i <= $#big_array ; $i++ ) {
+    my $items_data;
+    foreach my $subfield_code ( keys(%witness) ) {
+        $items_data .= "<td>" . $big_array[$i]{$subfield_code} . "</td>";
+    }
+    my %row_data;
+    $row_data{item_value} = $items_data;
+    push( @item_value_loop, \%row_data );
 }
 
-$template->param(item_loop => \@item_value_loop,
-                               item_header_loop => \@header_value_loop,
-                               biblionumber => $biblionumber
-);
-output_html_with_http_headers $query, $cookie, $template->output;
-
-sub get_authorised_value_desc ($$$$$) {
-   my($tag, $subfield, $value, $framework, $dbh) = @_;
+foreach my $subfield_code ( keys(%witness) ) {
+    my %header_value;
+    $header_value{header_value} = $witness{$subfield_code};
+    push( @header_value_loop, \%header_value );
+}
 
-   #---- branch
-    if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "branches" ) {
-#       return getbranchdetail($value)->{branchname};
-    }
+if(C4::Context->preference("ISBD")) {
+       $template->param(ISBD => 1);
+}
 
-   #---- itemtypes
-   if ($tagslib->{$tag}->{$subfield}->{'authorised_value'} eq "itemtypes" ) {
-#       return ItemType($value);
-    }
+$template->param(
+    item_loop        => \@item_value_loop,
+    item_header_loop => \@header_value_loop,
+    biblionumber     => $biblionumber,
+);
 
-   #---- "true" authorized value
-   my $category = $tagslib->{$tag}->{$subfield}->{'authorised_value'};
-
-   if ($category ne "") {
-       my $sth = $dbh->prepare("select lib from authorised_values where category = ? and authorised_value = ?");
-       $sth->execute($category, $value);
-       my $data = $sth->fetchrow_hashref;
-       return $data->{'lib'};
-   } else {
-       return $value; # if nothing is found return the original value
-   }
-}
+output_html_with_http_headers $query, $cookie, $template->output;
index 06d9595..198a1f5 100755 (executable)
@@ -1,5 +1,20 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 # wrriten 15/10/2002 by finlay@katipo.oc.nz
 # script to display borrowers account details in the opac
 
@@ -10,43 +25,47 @@ use C4::Members;
 use C4::Circulation::Circ2;
 use C4::Auth;
 use C4::Interface::CGI::Output;
-use HTML::Template;
+
 use C4::Date;
 
 my $query = new CGI;
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "opac-account.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-account.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
 my @bordat;
 $bordat[0] = $borr;
 
 $template->param( BORROWER_INFO => \@bordat );
 
-
 #get account details
-my ($numaccts,$accts,$total) = getboracctrecord(undef,$borr);
+my ( $numaccts, $accts, $total ) = getboracctrecord( undef, $borr );
 
-for (my $i=0;$i<$numaccts;$i++){
-       $accts->[$i]{'date'} = format_date($accts->[$i]{'date'});
-    $accts->[$i]{'amount'} = sprintf("%.2f", $accts->[$i]{'amount'});
-       if($accts->[$i]{'amount'} >= 0){
-               $accts->[$i]{'amountcredit'} = 1;
-       }
-    $accts->[$i]{'amountoutstanding'} =sprintf("%.2f", $accts->[$i]{'amountoutstanding'});
-       if($accts->[$i]{'amountoutstanding'} >= 0){
-               $accts->[$i]{'amountoutstandingcredit'} = 1;
-       }
-    if ($accts->[$i]{'accounttype'} ne 'F' && $accts->[$i]{'accounttype'} ne 'FU'){
-       $accts->[$i]{'print_title'};
+for ( my $i = 0 ; $i < $numaccts ; $i++ ) {
+    $accts->[$i]{'date'} = format_date( $accts->[$i]{'date'} );
+    $accts->[$i]{'amount'} = sprintf( "%.2f", $accts->[$i]{'amount'} );
+    if ( $accts->[$i]{'amount'} >= 0 ) {
+        $accts->[$i]{'amountcredit'} = 1;
+    }
+    $accts->[$i]{'amountoutstanding'} =
+      sprintf( "%.2f", $accts->[$i]{'amountoutstanding'} );
+    if ( $accts->[$i]{'amountoutstanding'} >= 0 ) {
+        $accts->[$i]{'amountoutstandingcredit'} = 1;
+    }
+    if (   $accts->[$i]{'accounttype'} ne 'F'
+        && $accts->[$i]{'accounttype'} ne 'FU' )
+    {
+        $accts->[$i]{'print_title'};
     }
 }
 
@@ -54,16 +73,14 @@ for (my $i=0;$i<$numaccts;$i++){
 my $num = 0;
 foreach my $row (@$accts) {
     $row->{'even'} = 1 if $num % 2 == 0;
-    $row->{'odd'} = 1 if $num % 2 == 1;
+    $row->{'odd'}  = 1 if $num % 2 == 1;
     $num++;
 }
 
-
-$template->param( ACCOUNT_LINES => $accts,
+$template->param (
+    ACCOUNT_LINES => $accts,
+    total => sprintf( "%.2f", $total )
 );
 
-$template->param( total => sprintf("%.2f",$total) );
-
-#$template->param(loggeninuser => $loggedinuser);
 output_html_with_http_headers $query, $cookie, $template->output;
 
index 470cd38..ce3a911 100755 (executable)
@@ -1,4 +1,5 @@
 #!/usr/bin/perl
+
 #script to provide bookshelf management
 # WARNING: This file uses 4-character tabs!
 #
@@ -22,7 +23,6 @@
 # Suite 330, Boston, MA  02111-1307 USA
 
 use strict;
-use C4::Search;
 use C4::Biblio;
 use CGI;
 use C4::Output;
@@ -30,99 +30,89 @@ use C4::BookShelves;
 use C4::Circulation::Circ2;
 use C4::Auth;
 use C4::Interface::CGI::Output;
-use HTML::Template;
 
-my $env;
-my $query = new CGI;
+my $query        = new CGI;
 my $biblionumber = $query->param('biblionumber');
-my $shelfnumber = $query->param('shelfnumber');
+my $shelfnumber  = $query->param('shelfnumber');
 my $newbookshelf = $query->param('newbookshelf');
-my $category = $query->param('category');
+my $category     = $query->param('category');
+
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-addbookbybiblionumber.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+    }
+);
 
-my ($template, $loggedinuser, $cookie)
-= get_template_and_user({template_name => "opac-addbookbybiblionumber.tmpl",
-                                                       query => $query,
-                                                       type => "opac",
-                                                       authnotrequired => 1,
-                                               });
+$shelfnumber = AddShelf( '', $newbookshelf, $loggedinuser, $category ) if $newbookshelf;
+
+# to know if we had to add more than one biblio.
+my $multiple = 0;
+$multiple = 1 if $biblionumber =~ /^(\d*\/)*$/;
 
-my $x; # for trash
-($x,$x,$shelfnumber) = AddShelf('',$newbookshelf,$loggedinuser,$category) if $newbookshelf;
 
 if ($shelfnumber) {
-       &AddToShelfFromBiblio($env, $biblionumber, $shelfnumber);
-       print "Content-Type: text/html\n\n<html><body onload=\"window.close()\"></body></html>";
-       exit;
-} else {
 
-       my  ( $bibliocount, @biblios )  = getbiblio($biblionumber);
+    if ($multiple){
+        foreach (split /\//,$biblionumber){
+            &AddToShelfFromBiblio($_,$shelfnumber);
+        }
+    }
+    else {
+        &AddToShelfFromBiblio( $biblionumber, $shelfnumber );
+    }
+    print $query->header;
+    print "<html><body onload=\"window.close();\"></body></html>";
+    exit;
+}
+else {
+    my ($shelflist) = GetShelves( $loggedinuser, 3 );
+    my @shelvesloop;
+    my %shelvesloop;
+    foreach my $element ( sort keys %$shelflist ) {
+        push( @shelvesloop, $element );
+            $shelvesloop{$element} = $shelflist->{$element}->{'shelfname'};
+    }
 
-       my ($shelflist) = GetShelfList($loggedinuser,3);
-       my @shelvesloop;
-       my %shelvesloop;
-       foreach my $element (sort keys %$shelflist) {
-                       push (@shelvesloop, $element);
-                       $shelvesloop{$element} = $shelflist->{$element}->{'shelfname'};
-       }
+    my $CGIbookshelves;
+    if ( @shelvesloop > 0 ) {
+        $CGIbookshelves = CGI::scrolling_list (
+            -name     => 'shelfnumber',
+            -values   => \@shelvesloop,
+            -labels   => \%shelvesloop,
+            -size     => 1,
+            -tabindex => '',
+            -multiple => 0
+        );
+    }
 
-       my $CGIbookshelves;
-       if (@shelvesloop > 0){
-       $CGIbookshelves=CGI::scrolling_list( -name     => 'shelfnumber',
-                               -values   => \@shelvesloop,
-                               -labels   => \%shelvesloop,
-                               -size     => 1,
-                               -tabindex=>'',
-                               -multiple => 0 );
-        }
+    if ( $multiple ) {
+        my @biblios;
+        foreach (split /\//,$biblionumber){
+            my $data = GetBiblioData($_);
+            push @biblios,$data;
+        }
+        $template->param (
+            multiple => 1,
+            biblionumber => $biblionumber,
+            total    => scalar @biblios,
+            biblios  => \@biblios,
+        );
+    }
+    else { # just one to add.
+        my $data = GetBiblioData( $biblionumber );
+        $template->param (
+            biblionumber => $biblionumber,
+            title        => $data->{'title'},
+            author       => $data->{'author'},
+        );
+    }
 
-       $template->param(biblionumber => $biblionumber,
-                               title => $biblios[0]->{'title'},
-                               author => $biblios[0]->{'author'},
-                               CGIbookshelves => $CGIbookshelves,
-                               LibraryName => C4::Context->preference("LibraryName"),
-                               suggestion => C4::Context->preference("suggestion"),
-                               virtualshelves => C4::Context->preference("virtualshelves"),
-                               OpacNav => C4::Context->preference("OpacNav"),
-                               opaccredits => C4::Context->preference("opaccredits"),
-                               opacsmallimage => C4::Context->preference("opacsmallimage"),
-                               opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
-                               opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
-       );
+    $template->param (
+        CGIbookshelves       => $CGIbookshelves,
+    );
 
-       output_html_with_http_headers $query, $cookie, $template->output;
+    output_html_with_http_headers $query, $cookie, $template->output;
 }
-# $Log$
-# Revision 1.5  2006/07/04 14:36:52  toins
-# Head & rel_2_2 merged
-#
-# Revision 1.4  2006/05/21 02:10:32  kados
-# syncing dev-week and HEAD
-#
-# Revision 1.1.2.6  2006/04/27 16:23:34  oleonard
-# Hiding option to add to existing virtual shelves if there are no existing virtual shelves (thanks Chris!)
-#
-# Revision 1.1.2.5  2006/03/01 22:33:25  oleonard
-# Enabling several new system preferences: opacreadinghistory, opaccolorstylesheet, opaclanguagesdisplay, opaclayoutstylesheet, opacsmallimage
-#
-# Revision 1.1.2.4  2006/02/04 16:47:21  kados
-# Adding support for opaccredits to opac scripts
-#
-# Revision 1.1.2.3  2006/02/03 21:03:57  kados
-# Updating script for new system preference: OpacNav
-# ----------------------------------------------------------------------
-#
-# Revision 1.1.2.2  2005/03/25 17:04:27  tipaul
-# adding virtual shelves & suggestions button to the top
-#
-# Revision 1.1.2.1  2005/03/10 08:44:43  tipaul
-# bugfix in baskets :
-# * The user does not need to have to have librarian rights to use virtual shelves
-# * error when adding a biblio to an existing basket
-#
-# Revision 1.1  2005/01/03 11:09:59  tipaul
-# *** empty log message ***
-#
-
-# Local Variables:
-# tab-width: 4
-# End:
index ae8037f..4e5d9d2 100755 (executable)
@@ -29,54 +29,62 @@ use C4::Context;
 use C4::Koha;
 use C4::Letters;
 use C4::Serials;
-# use C4::Search;
-use HTML::Template;
+
 
 my $query = new CGI;
-my $op = $query->param('op');
-my $dbh = C4::Context->dbh;
+my $op    = $query->param('op');
+my $dbh   = C4::Context->dbh;
 
 my $sth;
-my ($template, $loggedinuser, $cookie);
-my $externalid = $query->param('externalid');
-my $alerttype = $query->param('alerttype');
+my ( $template, $loggedinuser, $cookie );
+my $externalid   = $query->param('externalid');
+my $alerttype    = $query->param('alerttype');
 my $biblionumber = $query->param('biblionumber');
 
-($template, $loggedinuser, $cookie)
-       = get_template_and_user({template_name => "opac-alert-subscribe.tmpl",
-                               query => $query,
-                               type => "opac",
-                               authnotrequired => 1,
-                               debug => 1,
-                               });
+( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-alert-subscribe.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+        debug           => 1,
+    }
+);
+
+if ( $op eq 'alert_confirmed' ) {
+    addalert( $loggedinuser, $alerttype, $externalid );
+    if ( $alerttype eq 'issue' ) {
+        print $query->redirect(
+            "opac-serial-issues.pl?biblionumber=$biblionumber");
+        exit;
+    }
+}
+elsif ( $op eq 'cancel_confirmed' ) {
+    my $alerts = getalert( $loggedinuser, $alerttype, $externalid );
+    foreach (@$alerts)
+    {    # we are supposed to have only 1 result, but just in case...
+        delalert( $_->{alertid} );
+    }
+    if ( $alerttype eq 'issue' ) {
+        print $query->redirect(
+            "opac-serial-issues.pl?biblionumber=$biblionumber");
+        exit;
+    }
 
-if ($op eq 'alert_confirmed') {
-       addalert($loggedinuser,$alerttype,$externalid);
-       if ($alerttype eq 'issue') {
-               print $query->redirect("opac-serial-issues.pl?biblionumber=$biblionumber");
-               exit;
-       }
-} elsif ($op eq 'cancel_confirmed') {
-       my $alerts =getalert($loggedinuser,$alerttype,$externalid);
-       foreach (@$alerts) { # we are supposed to have only 1 result, but just in case...
-               delalert($_->{alertid});
-       }
-       if ($alerttype eq 'issue') {
-               print $query->redirect("opac-serial-issues.pl?biblionumber=$biblionumber");
-               exit;
-       }
+}
+else {
+    if ( $alerttype eq 'issue' ) {    # alert for subscription issues
+        my $subscription = &GetSubscription($externalid);
+        $template->param(
+            "typeissue$op" => 1,
+            bibliotitle    => $subscription->{bibliotitle},
+            notes          => $subscription->{notes},
+            externalid     => $externalid,
+            biblionumber   => $biblionumber,
+        );
+    }
+    else {
+    }
 
-} else {
-       if ($alerttype eq 'issue') { # alert for subscription issues
-               my $subscription = &GetSubscription($externalid);
-               $template->param("typeissue$op" => 1,
-                                               bibliotitle => $subscription->{bibliotitle},
-                                               notes => $subscription->{notes},
-                                               externalid => $externalid,
-                                               biblionumber => $biblionumber,
-                                               );
-       } else {
-       }
-       
 }
 output_html_with_http_headers $query, $cookie, $template->output;
index 340140e..ffb7129 100755 (executable)
@@ -1,65 +1,92 @@
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+# $Id$
+
 use strict;
 require Exporter;
 use CGI;
 use C4::Biblio;
 use C4::Auth;
 use C4::Interface::CGI::Output;
-use HTML::Template;
 
-my $query=new CGI;
-
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "opac-basket.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                        });
+my $query = new CGI;
 
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user (
+    {
+        template_name   => "opac-basket.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+        flagsrequired   => { borrow => 1 },
+    }
+);
 
-my $bib_list=$query->param('bib_list');
-my $print_basket=$query->param('print');
-my $verbose = $query->param('verbose');
+my $bib_list     = $query->param('bib_list');
+my $print_basket = $query->param('print');
+my $verbose      = $query->param('verbose');
 
-if($verbose) { $template->param(verbose => 1); }
-if ($print_basket) { $template->param(print_basket => 1); }
+if ($verbose)      { $template->param( verbose      => 1 ); }
+if ($print_basket) { $template->param( print_basket => 1 ); }
 
-my @bibs = split(/\//, $bib_list);
+my @bibs = split( /\//, $bib_list );
 my @results;
 
 my $num = 1;
-foreach my $biblionumber (@bibs) {
-       $template->param(biblionumber => $biblionumber);
-
-       my $dat                                   = &bibdata($biblionumber);
-       my ($authorcount, $addauthor)             = &addauthor($biblionumber);
-       my @items                                 = &ItemInfo(undef, $biblionumber, 'opac');
-
-       $dat->{'additional'}=$addauthor->[0]->{'author'};
-       for (my $i = 1; $i < $authorcount; $i++) {
-                       $dat->{'additional'} .= "|" . $addauthor->[$i]->{'author'};
-       } # for
-       if($num % 2 == 1){
-               $dat->{'even'} = 1;
-       }
-       $num++;
-       $dat->{'biblionumber'} = $biblionumber;
-       $dat->{ITEM_RESULTS} = \@items;
-       if (C4::Context->preference("BiblioDefaultView") eq "normal") {
-            $dat->{dest} = "opac-detail.pl";
-       } elsif (C4::Context->preference("BiblioDefaultView") eq "marc") {
-            $dat->{dest} ="opac-MARCdetail.pl";
-       } else {
-            $dat->{dest} = "opac-ISBDdetail.pl";
-       }
-       push (@results, $dat);
+my $marcflavour = C4::Context->preference('marcflavour');
+foreach my $biblionumber ( @bibs ) {
+    $template->param( biblionumber => $biblionumber );
+
+    my $dat              = &GetBiblioData($biblionumber);
+    my $record           = &GetMarcBiblio($biblionumber);
+    my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
+    my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
+    my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
+    my @items            = &GetItemsInfo( $biblionumber, 'opac' );
+
+    if ( $num % 2 == 1 ) {
+        $dat->{'even'} = 1;
+    }
+
+    $num++;
+    $dat->{biblionumber} = $biblionumber;
+    $dat->{ITEM_RESULTS}   = \@items;
+    $dat->{MARCNOTES}      = $marcnotesarray;
+    $dat->{MARCSUBJCTS}    = $marcsubjctsarray;
+    $dat->{MARCAUTHORS}    = $marcauthorsarray;
+
+    if ( C4::Context->preference("BiblioDefaultView") eq "normal" ) {
+        $dat->{dest} = "opac-detail.pl";
+    }
+    elsif ( C4::Context->preference("BiblioDefaultView") eq "marc" ) {
+        $dat->{dest} = "opac-MARCdetail.pl";
+    }
+    else {
+        $dat->{dest} = "opac-ISBDdetail.pl";
+    }
+    push( @results, $dat );
 }
 
-my $resultsarray=\@results;
+my $resultsarray = \@results;
+
 # my $itemsarray=\@items;
 
-$template->param(BIBLIO_RESULTS => $resultsarray,
+$template->param(
+    BIBLIO_RESULTS => $resultsarray,
 );
 
 output_html_with_http_headers $query, $cookie, $template->output;
index 9007f86..2d03c31 100755 (executable)
@@ -25,11 +25,12 @@ use CGI;
 use C4::Auth;
 use C4::Serials;    #uses getsubscriptionfrom biblionumber
 use C4::Interface::CGI::Output;
-use HTML::Template;
 use C4::Biblio;
-use C4::Search;
 use C4::Amazon;
 use C4::Review;
+use C4::Serials;
+use C4::Members;
+
 
 my $query = new CGI;
 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
@@ -42,16 +43,12 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
     }
 );
 
-my $biblionumber = $query->param('bib');
+my $biblionumber = $query->param('biblionumber') || $query->param('bib');
 $template->param( biblionumber => $biblionumber );
 
 # change back when ive fixed request.pl
-my @items = &ItemInfo( undef, $biblionumber, 'opac' );
-my $dat = &bibdata($biblionumber);
-my ( $authorcount,        $addauthor )      = &addauthor($biblionumber);
-my ( $webbiblioitemcount, @webbiblioitems ) = &getwebbiblioitems($biblionumber);
-my ( $websitecount,       @websites )       = &getwebsites($biblionumber);
-
+my @items = &GetItemsInfo( $biblionumber, 'opac' );
+my $dat = &GetBiblioData($biblionumber);
 #coping with subscriptions
 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
 my @subscriptions       =
@@ -69,109 +66,66 @@ foreach my $subscription (@subscriptions) {
 }
 
 $dat->{'count'} = @items;
-my @author;
-if ( $dat->{'author'} ) {
-    my %authorpush;
-    $authorpush{author} = $dat->{'author'};
-    push @author, \%authorpush;
-}
-$dat->{'additional'} = $addauthor->[0]->{'author'};
-if ( $dat->{'additional'} ) {
-    my %authorpush;
-    $authorpush{author} = $addauthor->[0]->{'author'};
-    push @author, \%authorpush;
-}
-my @title;
-foreach my $word ( split( " ", $dat->{'title'} ) ) {
-    unless ( length($word) == 4 ) {
-        $word =~ s/\%//g;
-    }
-    unless ( C4::Context->stopwords->{ uc($word) } or length($word) == 1 ) {
-        my %titlepush;
-        $titlepush{title} = $word;
-        push @title, \%titlepush;
-    }    #it's NOT a stopword => use it. Otherwise, ignore
-}
-
-for ( my $i = 1 ; $i < $authorcount ; $i++ ) {
-    $dat->{'additional'} .= " ; " . $addauthor->[$i]->{'author'};
 
-    my %authorpush;
-    $authorpush{author} = $addauthor->[$i]->{'author'};
-    push @author, \%authorpush;
-}    # for
+#adding RequestOnOpac filter to allow or not the display of plce reserve button
+# FIXME - use me or delete me.
+my $RequestOnOpac;
+if (C4::Context->preference("RequestOnOpac")) {
+       $RequestOnOpac = 1;
+}
 
 my $norequests = 1;
 foreach my $itm (@items) {
     $norequests = 0
       unless ( ( $itm->{'wthdrawn'} )
         || ( $itm->{'itemlost'} )
-        || ( $itm->{'notforloan'} )
         || ( $itm->{'itemnotforloan'} )
         || ( !$itm->{'itemnumber'} ) );
     $itm->{ $itm->{'publictype'} } = 1;
 }
 
-$template->param( norequests => $norequests );
+$template->param( norequests => $norequests, );
 
 ## get notes and subjects from MARC record
-my $marc    = C4::Context->preference("marc");
+    my $dbh              = C4::Context->dbh;
+    my $marcflavour      = C4::Context->preference("marcflavour");
+    my $record           = GetMarcBiblio($biblionumber);
+    my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
+    my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
+    my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
+       my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
+
+    $template->param(
+        MARCNOTES   => $marcnotesarray,
+        MARCSUBJCTS => $marcsubjctsarray,
+        MARCAUTHORS => $marcauthorsarray,
+               MARCSERIES  => $marcseriesarray
+    );
+
 my @results = ( $dat, );
-if ( C4::Boolean::true_p($marc) ) {
-    my $dbh = C4::Context->dbh;
-    my $bibid = &MARCfind_MARCbibid_from_oldbiblionumber( $dbh, $biblionumber );
-    my $marcflavour = C4::Context->preference("marcflavour");
-    my $marcnotesarray = &getMARCnotes( $dbh, $bibid, $marcflavour );
-    $results[0]->{MARCNOTES} = $marcnotesarray;
-    my $marcsubjctsarray = &getMARCsubjects( $dbh, $bibid, $marcflavour );
-    $results[0]->{MARCSUBJCTS} = $marcsubjctsarray;
-
-    #  $template->param(MARCNOTES => $marcnotesarray);
-    #  $template->param(MARCSUBJCTS => $marcsubjctsarray);
+foreach ( keys %{$dat} ) {
+    $template->param( "$_" => $dat->{$_} . "" );
 }
 
-# get the number of reviews
-my $reviewcount = numberofreviews($biblionumber);
-$dat->{'reviews'} = $reviewcount;
-
-my @results      = ( $dat, );
-my $resultsarray = \@results;
-my $itemsarray   = \@items;
-my $webarray     = \@webbiblioitems;
-my $sitearray    = \@websites;
-my $titlewords   = \@title;
-my $authorwords  = \@author;
-
-#coping with subscriptions
-my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
-my @subscriptions       =
-  GetSubscriptions( $dat->{title}, $dat->{issn}, $biblionumber );
-my @subs;
-foreach my $subscription (@subscriptions) {
-    warn "subsid :" . $subscription->{subscriptionid};
-    my %cell;
-    $cell{subscriptionid}    = $subscription->{subscriptionid};
-    $cell{subscriptionnotes} = $subscription->{notes};
-
-    #get the three latest serials.
-    $cell{latestserials} =
-      GetLatestSerials( $subscription->{subscriptionid}, 3 );
-    push @subs, \%cell;
+my $reviews = getreviews( $biblionumber, 1 );
+foreach ( @$reviews ) {
+    my $borrower_number_review = $_->{borrowernumber};
+    my $borrowerData           = GetMember('',$borrower_number_review);
+    # setting some borrower info into this hash
+    $_->{title}     = $borrowerData->{'title'};
+    $_->{surname}   = $borrowerData->{'surname'};
+    $_->{firstname} = $borrowerData->{'firstname'};
 }
 
 $template->param(
-    BIBLIO_RESULTS      => $resultsarray,
-    ITEM_RESULTS        => $itemsarray,
-    WEB_RESULTS         => $webarray,
-    SITE_RESULTS        => $sitearray,
+    ITEM_RESULTS        => \@items,
+    subscriptionsnumber => $subscriptionsnumber,
+    biblionumber        => $biblionumber,
+    subscriptions       => \@subs,
     subscriptionsnumber => $subscriptionsnumber,
-    LibraryName         => C4::Context->preference("LibraryName"),
-    suggestion          => C4::Context->preference("suggestion"),
-    virtualshelves      => C4::Context->preference("virtualshelves"),
-    titlewords          => $titlewords,
-    authorwords         => $authorwords,
-    reviewson           => C4::Context->preference("marc"),
+    reviews             => $reviews
 );
+
 ## Amazon.com stuff
 #not used unless preference set
 if ( C4::Context->preference("AmazonContent") == 1 ) {
@@ -210,6 +164,6 @@ if ( C4::Context->preference("AmazonContent") == 1 ) {
         }
     }
     $template->param( SIMILAR_PRODUCTS => \@products );
-    $template->param( REVIEWS          => \@reviews );
+    $template->param( AMAZONREVIEWS    => \@reviews );
 }
 output_html_with_http_headers $query, $cookie, $template->output;
index 60eb240..c8aef6b 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-use HTML::Template;
 use strict;
 require Exporter;
 use C4::Context;
-use C4::Output;  # contains gettemplate
+use C4::Output;    # contains gettemplate
 use CGI;
 use C4::Biblio;
 use C4::Auth;
 use C4::Interface::CGI::Output;
 use C4::Date;
 
-my $query=new CGI;
-my $type=$query->param('type');
-($type) || ($type='intra');
+my $query = new CGI;
+my $type  = $query->param('type');
+($type) || ( $type = 'intra' );
 
-my $biblionumber=$query->param('bib');
+my $biblionumber = $query->param('biblionumber');
 
 # change back when ive fixed request.pl
-my @items = ItemInfo(undef, $biblionumber, $type);
+my @items      = GetItemInfosOf($biblionumber);
 my $norequests = 1;
 foreach my $itm (@items) {
-     $norequests = 0 unless $itm->{'notforloan'};
+    $norequests = 0 unless $itm->{'notforloan'};
 }
 
+my $dat       = GetBiblioData($biblionumber);
+my $record    = GetMarcBiblio($biblionumber);
+my $addauthor =
+  GetMarcAuthors( $record, C4::Context->preference("marcflavour") );
+my $authorcount = scalar @$addauthor;
 
-
-my $dat=bibdata($biblionumber);
-my ($authorcount, $addauthor)= &getaddauthor($biblionumber);
-my ($webbiblioitemcount, @webbiblioitems) = &getwebbiblioitems($biblionumber);
-my ($websitecount, @websites)             = &getwebsites($biblionumber);
-
-$dat->{'count'}=@items;
+$dat->{'count'}      = @items;
 $dat->{'norequests'} = $norequests;
 
-$dat->{'additional'}=$addauthor->[0]->{'author'};
-for (my $i = 1; $i < $authorcount; $i++) {
-        $dat->{'additional'} .= "|" . $addauthor->[$i]->{'author'};
-} # for
+$dat->{'additional'} = "";
+foreach (@$addauthor) {
+    $dat->{'additional'} .= "|" . $_->{'value'};
+}    # for
 
 my @results;
 
-$results[0]=$dat;
+$results[0] = $dat;
 
-my $resultsarray=\@results;
-my $itemsarray=\@items;
-my $webarray=\@webbiblioitems;
-my $sitearray=\@websites;
+my $resultsarray = \@results;
+my $itemsarray   = \@items;
 
-my $startfrom=$query->param('startfrom');
-($startfrom) || ($startfrom=0);
+my $startfrom = $query->param('startfrom');
+($startfrom) || ( $startfrom = 0 );
 
-my ($template, $loggedinuser, $cookie) = get_template_and_user({
-       template_name   => ('opac-detailprint.tmpl'),
-       query           => $query,
-       type            => "opac",
-       authnotrequired => 1,
-    });
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => ('opac-detailprint.tmpl'),
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+    }
+);
 
-my $count=1;
+my $count = 1;
 
 # now to get the items into a hash we can use and whack that thru
 
-
-my $nextstartfrom=($startfrom+20<$count-20) ? ($startfrom+20) : ($count-20);
-my $prevstartfrom=($startfrom-20>0) ? ($startfrom-20) : (0);
-$template->param(startfrom => $startfrom+1,
-                                               endat => $startfrom+20,
-                                               numrecords => $count,
-                                               nextstartfrom => $nextstartfrom,
-                                               prevstartfrom => $prevstartfrom,
-                                               BIBLIO_RESULTS => $resultsarray,
-                                               ITEM_RESULTS => $itemsarray,
-                                               WEB_RESULTS => $webarray,
-                                               SITE_RESULTS => $sitearray,
-                                               loggedinuser => $loggedinuser,
-                                               biblionumber => $biblionumber,
-                                               );
+my $nextstartfrom =
+  ( $startfrom + 20 < $count - 20 ) ? ( $startfrom + 20 ) : ( $count - 20 );
+my $prevstartfrom = ( $startfrom - 20 > 0 ) ? ( $startfrom - 20 ) : (0);
+$template->param(
+    startfrom      => $startfrom + 1,
+    endat          => $startfrom + 20,
+    numrecords     => $count,
+    nextstartfrom  => $nextstartfrom,
+    prevstartfrom  => $prevstartfrom,
+    BIBLIO_RESULTS => $resultsarray,
+    ITEM_RESULTS   => $itemsarray,
+    loggedinuser   => $loggedinuser,
+    biblionumber   => $biblionumber,
+);
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
-
 # Local Variables:
 # tab-width: 8
 # End:
index a75756f..22398b6 100755 (executable)
@@ -1,6 +1,5 @@
 #!/usr/bin/perl
 
-
 # Copyright 2000-2002 Katipo Communications
 #
 # This file is part of Koha.
@@ -27,7 +26,7 @@ use C4::Search;
 use C4::AuthoritiesMarc;
 use C4::Context;
 use C4::Biblio;
-use HTML::Template;
+
 
 =head1 NAME
 
@@ -48,201 +47,242 @@ The script shows all results & the user can choose what he want, that is copied
 =cut
 
 my $input = new CGI;
-my $field =$input->param('marclist');
+my $field = $input->param('marclist');
+
 #warn "field :$field";
-my ($tablename, $kohafield)=split /./,$field;
+my ( $tablename, $kohafield ) = split /./, $field;
+
 #my $tablename=$input->param('tablename');
-$tablename="biblio" unless ($tablename);
+$tablename = "biblio" unless ($tablename);
+
 #my $kohafield = $input->param('kohafield');
 my @search = $input->param('search');
+
 # warn " ".$search[0];
 my $index = $input->param('index');
+
 # warn " index: ".$index;
-my $op=$input->param('op');
-if (($search[0]) and not ($op eq 'do_search')){
-       $op='do_search';
+my $op = $input->param('op');
+if ( ( $search[0] ) and not( $op eq 'do_search' ) ) {
+    $op = 'do_search';
 }
 my $script_name = 'opac-dictionary.pl';
 my $query;
-my $type=$input->param('type');
+my $type = $input->param('type');
+
 #warn " ".$type;
 
 my $dbh = C4::Context->dbh;
-my ($template, $loggedinuser, $cookie);
+my ( $template, $loggedinuser, $cookie );
 
 my $env;
 
-my $startfrom=$input->param('startfrom');
-$startfrom=0 if(!defined $startfrom);
+my $startfrom = $input->param('startfrom');
+$startfrom = 0 if ( !defined $startfrom );
 my $searchdesc;
 my $resultsperpage;
 
 #warn "Starting process";
 
-if ($op eq "do_search") {
-       #
-       # searching in biblio
-       #
-       my $sth=$dbh->prepare("Select distinct tagfield,tagsubfield from marc_subfield_structure where kohafield = ?");
-       $sth->execute("$field");
-       my (@tags, @and_or, @operator, @excluding,@value);
-       
-       while ((my $tagfield,my $tagsubfield,my $liblibrarian) = $sth->fetchrow) {
-               push @tags, $dbh->quote("$tagfield$tagsubfield");
-       }
-
-       $resultsperpage= $input->param('resultsperpage');
-       $resultsperpage = 19 if(!defined $resultsperpage);
-       my $orderby = $input->param('orderby');
-
-       findseealso($dbh,\@tags);
-
-       my @results, my $total;
-       my $strsth="select distinct subfieldvalue, count(marc_subfield_table.bibid) from marc_subfield_table,marc_word where marc_word.word like ? and marc_subfield_table.bibid=marc_word.bibid and marc_subfield_table.tagorder=marc_word.tagorder and marc_word.tagsubfield in ";
-       my $listtags="(";
-       foreach my $tag (@tags){
-               $listtags .= $tag .",";
-       }
-       $listtags =~s/,$/)/;
-       $strsth .= $listtags." and marc_word.tagsubfield=concat(marc_subfield_table.tag,marc_subfield_table.subfieldcode) group by subfieldvalue ";
-#      warn "search in biblio : ".$strsth;
-       my $value = uc($search[0]);
-       $value=~s/\*/%/g;
-       $value.= "%" if not($value=~m/%/);
-#      warn " texte : ".$value;
-
-       $sth=$dbh->prepare($strsth);
-       $sth->execute($value);
-       my $total;
-       my @catresults;
-       while (my ($value,$ctresults)=$sth->fetchrow) {
-#              warn "countresults : ".$ctresults;
-               push @catresults,{value=> $value, 
-                                                 even=>($total-$startfrom*$resultsperpage)%2,
-                                                 count=>$ctresults
-                                                 } if (($total>=$startfrom*$resultsperpage) and ($total<($startfrom+1)*$resultsperpage));
-               $total++;
-       }
-       
-
-       my $strsth="Select distinct authtypecode from marc_subfield_structure where (";
-       foreach my $listtags (@tags){
-               my @taglist=split /,/,$listtags;
-               foreach my $curtag (@taglist){
-                       $strsth.="(tagfield='".substr($curtag,1,3)."' AND tagsubfield='".substr($curtag,4,1)."') OR";
-               }
-       }
-       
-       $strsth=~s/ OR$/)/;
-       my $strsth = $strsth." and authtypecode is not NULL";
-#      warn $strsth;
-       my $sth=$dbh->prepare($strsth);
-       $sth->execute;
-       
-       #
-       # searching in authorities
-       #
-       my @authresults;
-       my $authnbresults;
-       while ((my $authtypecode) = $sth->fetchrow) {
-               my ($curauthresults,$nbresults) = authoritysearch($dbh,[''],[''],[''],['contains'],
-                                                                                                               \@search,$startfrom*$resultsperpage, $resultsperpage,$authtypecode);
-               push @authresults, @$curauthresults;
-               $authnbresults+=$nbresults;
-#              warn "auth : $authtypecode nbauthresults : $nbresults";
-       }
-       
-       # 
-       # OK, filling the template with authorities & biblio entries found.
-       #
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-dictionary.tmpl",
-                               query => $input,
-                               type => 'opac',
-                               authnotrequired => 1,
-                               debug => 1,
-                               });
-
-       # multi page display gestion
-       my $displaynext=0;
-       my $displayprev=$startfrom;
-       if(($total - (($startfrom+1)*($resultsperpage))) > 0 ) {
-               $displaynext = 1;
-       }
-
-       my @field_data = ();
-
-       for(my $i = 0 ; $i <= $#tags ; $i++) {
-               push @field_data, { term => "marclist", val=>$tags[$i] };
-               push @field_data, { term => "and_or", val=>$and_or[$i] };
-               push @field_data, { term => "excluding", val=>$excluding[$i] };
-               push @field_data, { term => "operator", val=>$operator[$i] };
-               push @field_data, { term => "value", val=>$value[$i] };
-       }
-
-       my @numbers = ();
-
-       if ($total>$resultsperpage) {
-               for (my $i=1; $i<$total/$resultsperpage+1; $i++) {
-                       if ($i<16) {
-                       my $highlight=0;
-                       ($startfrom==($i-1)) && ($highlight=1);
-                       push @numbers, { number => $i,
-                                       highlight => $highlight ,
-                                       searchdata=> \@field_data,
-                                       startfrom => ($i-1)};
-                       }
-       }
-       }
-
-       my $from = $startfrom*$resultsperpage+1;
-       my $to;
-
-       if($total < (($startfrom+1)*$resultsperpage))
-       {
-               $to = $total;
-       } else {
-               $to = (($startfrom+1)*$resultsperpage);
-       }
-       $template->param(anindex => $input->param('index'),
-       opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
-        opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
-       );
-       $template->param(result => \@results,
-                                        catresult=> \@catresults,
-                                               search => $search[0],
-                                               marclist =>$field,
-                                               authresult => \@authresults,
-                                               nbresults => $authnbresults,
-                                               startfrom=> $startfrom,
-                                               displaynext=> $displaynext,
-                                               displayprev=> $displayprev,
-                                               resultsperpage => $resultsperpage,
-                                               startfromnext => $startfrom+1,
-                                               startfromprev => $startfrom-1,
-                                               searchdata=>\@field_data,
-                                               total=>$total,
-                                               from=>$from,
-                                               to=>$to,
-                                               numbers=>\@numbers,
-                                               MARC_ON => C4::Context->preference("marc"),
-                                               );
-
- } else {
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-dictionary.tmpl",
-                               query => $input,
-                               type => 'opac',
-                               authnotrequired => 1,
-                               debug => 1,
-                               });
-#warn "type : $type";
- }
-$template->param(search => $search[0],
-                                       marclist =>$field,
-                                       type=>$type,
-                                       anindex => $input->param('index'));
+if ( $op eq "do_search" ) {
+
+    #
+    # searching in biblio
+    #
+    my $sth =
+      $dbh->prepare(
+"Select distinct tagfield,tagsubfield from marc_subfield_structure where kohafield = ?"
+      );
+    $sth->execute("$field");
+    my ( @tags, @and_or, @operator, @excluding, @value );
+
+    while ( ( my $tagfield, my $tagsubfield, my $liblibrarian ) =
+        $sth->fetchrow )
+    {
+        push @tags, $dbh->quote("$tagfield$tagsubfield");
+    }
+
+    $resultsperpage = $input->param('resultsperpage');
+    $resultsperpage = 19 if ( !defined $resultsperpage );
+    my $orderby = $input->param('orderby');
+
+    findseealso( $dbh, \@tags );
+
+    my @results, my $total;
+    my $strsth =
+"select distinct subfieldvalue, count(marc_subfield_table.bibid) from marc_subfield_table,marc_word where marc_word.word like ? and marc_subfield_table.bibid=marc_word.bibid and marc_subfield_table.tagorder=marc_word.tagorder and marc_word.tagsubfield in ";
+    my $listtags = "(";
+    foreach my $tag (@tags) {
+        $listtags .= $tag . ",";
+    }
+    $listtags =~ s/,$/)/;
+    $strsth .= $listtags
+      . " and marc_word.tagsubfield=concat(marc_subfield_table.tag,marc_subfield_table.subfieldcode) group by subfieldvalue ";
+
+    #     warn "search in biblio : ".$strsth;
+    my $value = uc( $search[0] );
+    $value =~ s/\*/%/g;
+    $value .= "%" if not( $value =~ m/%/ );
+
+    #     warn " texte : ".$value;
+
+    $sth = $dbh->prepare($strsth);
+    $sth->execute($value);
+    my @catresults;
+    while ( my ( $value, $ctresults ) = $sth->fetchrow ) {
+
+        #         warn "countresults : ".$ctresults;
+        push @catresults,
+          {
+            value => $value,
+            even  => ( $total - $startfrom * $resultsperpage ) % 2,
+            count => $ctresults
+          }
+          if (  ( $total >= $startfrom * $resultsperpage )
+            and ( $total < ( $startfrom + 1 ) * $resultsperpage ) );
+        $total++;
+    }
+
+    $strsth =
+      "Select distinct authtypecode from marc_subfield_structure where (";
+    foreach my $listtags (@tags) {
+        my @taglist = split /,/, $listtags;
+        foreach my $curtag (@taglist) {
+            $strsth .=
+                "(tagfield='"
+              . substr( $curtag, 1, 3 )
+              . "' AND tagsubfield='"
+              . substr( $curtag, 4, 1 ) . "') OR";
+        }
+    }
+
+    $strsth =~ s/ OR$/)/;
+    $strsth = $strsth . " and authtypecode is not NULL";
+
+    #     warn $strsth;
+    $sth = $dbh->prepare($strsth);
+    $sth->execute;
+
+    #
+    # searching in authorities
+    #
+    my @authresults;
+    my $authnbresults;
+    while ( ( my $authtypecode ) = $sth->fetchrow ) {
+        my ( $curauthresults, $nbresults ) =
+          authoritysearch( $dbh, [''], [''], [''], ['contains'], \@search,
+            $startfrom * $resultsperpage,
+            $resultsperpage, $authtypecode );
+        push @authresults, @$curauthresults;
+        $authnbresults += $nbresults;
+
+        #        warn "auth : $authtypecode nbauthresults : $nbresults";
+    }
+
+    #
+    # OK, filling the template with authorities & biblio entries found.
+    #
+    ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-dictionary.tmpl",
+            query           => $input,
+            type            => 'opac',
+            authnotrequired => 1,
+            debug           => 1,
+        }
+    );
+
+    # multi page display gestion
+    my $displaynext = 0;
+    my $displayprev = $startfrom;
+    if ( ( $total - ( ( $startfrom + 1 ) * ($resultsperpage) ) ) > 0 ) {
+        $displaynext = 1;
+    }
+
+    my @field_data = ();
+
+    for ( my $i = 0 ; $i <= $#tags ; $i++ ) {
+        push @field_data, { term => "marclist",  val => $tags[$i] };
+        push @field_data, { term => "and_or",    val => $and_or[$i] };
+        push @field_data, { term => "excluding", val => $excluding[$i] };
+        push @field_data, { term => "operator",  val => $operator[$i] };
+        push @field_data, { term => "value",     val => $value[$i] };
+    }
+
+    my @numbers = ();
+
+    if ( $total > $resultsperpage ) {
+        for ( my $i = 1 ; $i < $total / $resultsperpage + 1 ; $i++ ) {
+            if ( $i < 16 ) {
+                my $highlight = 0;
+                ( $startfrom == ( $i - 1 ) ) && ( $highlight = 1 );
+                push @numbers,
+                  {
+                    number     => $i,
+                    highlight  => $highlight,
+                    searchdata => \@field_data,
+                    startfrom  => ( $i - 1 )
+                  };
+            }
+        }
+    }
+
+    my $from = $startfrom * $resultsperpage + 1;
+    my $to;
+
+    if ( $total < ( ( $startfrom + 1 ) * $resultsperpage ) ) {
+        $to = $total;
+    }
+    else {
+        $to = ( ( $startfrom + 1 ) * $resultsperpage );
+    }
+    $template->param(
+        anindex              => $input->param('index'),
+        opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
+        opaccolorstylesheet  => C4::Context->preference("opaccolorstylesheet"),
+    );
+    $template->param(
+        result         => \@results,
+        catresult      => \@catresults,
+        search         => $search[0],
+        marclist       => $field,
+        authresult     => \@authresults,
+        nbresults      => $authnbresults,
+        startfrom      => $startfrom,
+        displaynext    => $displaynext,
+        displayprev    => $displayprev,
+        resultsperpage => $resultsperpage,
+        startfromnext  => $startfrom + 1,
+        startfromprev  => $startfrom - 1,
+        searchdata     => \@field_data,
+        total          => $total,
+        from           => $from,
+        to             => $to,
+        numbers        => \@numbers,
+        MARC_ON        => C4::Context->preference("marc"),
+    );
+
+}
+else {
+    ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-dictionary.tmpl",
+            query           => $input,
+            type            => 'opac',
+            authnotrequired => 1,
+            debug           => 1,
+        }
+    );
+
+    #warn "type : $type";
+
+}
+$template->param(
+    search   => $search[0],
+    marclist => $field,
+    type     => $type,
+    anindex  => $input->param('index')
+);
 
 # Print the page
 output_html_with_http_headers $input, $cookie, $template->output;
index e110cfe..b73ea3c 100755 (executable)
@@ -1,86 +1,58 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use CGI;
 use C4::Context;
 use C4::Output;
-use HTML::Template;
-
-my $query=new CGI;
-
-my $sessionID=$query->cookie('sessionID');
-
-
-if ($ENV{'REMOTE_USER'}) {
-    print $query->header();
-    print startpage();
-    print startmenu('catalogue');
-    print qq|
-<h1>Logout Feature Not Available</h1>
-Your Koha server is configured to use a type of authentication called "Basic
-Authentication" instead of using a cookies-based authentication system.  With
-Basic Authentication, the only way to logout of Koha is by exiting your
-browser.
-|;
-    print endmenu('catalogue');
-    print endpage();
-    exit;
-}
-
-my $sessions;
-open (S, "/tmp/sessions");
-       # FIXME - Come up with a better logging mechanism
-while (my ($sid, $u, $lasttime) = split(/:/, <S>)) {
-    chomp $lasttime;
-    (next) unless ($sid);
-    (next) if ($sid eq $sessionID);
-    $sessions->{$sid}->{'userid'}=$u;
-    $sessions->{$sid}->{'lasttime'}=$lasttime;
-}
-open (S, ">/tmp/sessions");
-foreach (keys %$sessions) {
-    my $userid=$sessions->{$_}->{'userid'};
-    my $lasttime=$sessions->{$_}->{'lasttime'};
-    print S "$_:$userid:$lasttime\n";
-}
 
+my $query = new CGI;
+my $sessionID = $query->cookie('sessionID');
 my $dbh = C4::Context->dbh;
 
 # Check that this is the ip that created the session before deleting it
-
-my $sth=$dbh->prepare("select userid,ip from sessions where sessionID=?");
+my $sth = $dbh->prepare("select userid,ip from sessions where sessionID=?");
 $sth->execute($sessionID);
-my ($userid, $ip);
-if ($sth->rows) {
-    ($userid,$ip) = $sth->fetchrow;
-    if ($ip ne $ENV{'REMOTE_ADDR'}) {
-       # attempt to logout from a different ip than cookie was created at
-       exit;
+my ( $userid, $ip );
+if ( $sth->rows ) {
+    ( $userid, $ip ) = $sth->fetchrow;
+    if ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+
+        # attempt to logout from a different ip than cookie was created at
+        exit;
     }
 }
 
-my $sth=$dbh->prepare("delete from sessions where sessionID=?");
+$sth = $dbh->prepare("delete from sessions where sessionID=?");
 $sth->execute($sessionID);
 open L, ">>/tmp/sessionlog";
-my $time=localtime(time());
-printf L "%20s from %16s logged out at %30s (manual log out).\n", $userid, $ip, $time;
+my $time = localtime( time() );
+printf L "%20s from %16s logged out at %30s (manual log out).\n", $userid, $ip,
+  $time;
 close L;
 
-my $cookie=$query->cookie(-name => 'sessionID',
-                         -value => '',
-                         -expires => '+1y');
+my $cookie = $query->cookie(
+    -name    => 'sessionID',
+    -value   => '',
+    -expires => '+1y'
+);
 
 # Should redirect to opac home page after logging out
 
 print $query->redirect("/cgi-bin/koha/opac-main.pl");
 
 exit;
-if ($sessionID) {
-    print "Logged out of $sessionID<br>\n";
-    print "<a href=shelves.pl>Login</a>";
-} else {
-    print "Not logged in.<br>\n";
-    print "<a href=shelves.pl>Login</a>";
-}
-
-
 
index b65229e..7232716 100755 (executable)
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+# $Id$
+
 use strict;
 require Exporter;
 use CGI;
-use HTML::Template;
-
-use C4::Context;
-use C4::Auth;       # get_template_and_user
+use C4::Auth;    # get_template_and_user
 use C4::Interface::CGI::Output;
 use C4::BookShelves;
-use C4::Koha;
-use C4::Members;
+use C4::Languages;           # getTranslatedLanguages
+use C4::Branch;         # GetBranches
+use C4::Members;        # GetMember
+use C4::NewsChannels;   # get_opac_news
+use C4::Acquisition;    # GetRecentAcqui
 
 my $input = new CGI;
-my $kohaVersion = C4::Context->config("kohaversion");
-my $dbh = C4::Context->dbh;
-my $query="Select itemtype,description from itemtypes order by description";
-my $sth=$dbh->prepare($query);
-$sth->execute;
-my  @itemtypeloop;
-my %itemtypes;
-while (my ($value,$lib) = $sth->fetchrow_array) {
-       my %row =(      value => $value,
-                               description => $lib,
-                       );
-       push @itemtypeloop, \%row;
-}
-$sth->finish;
+my $dbh   = C4::Context->dbh;
+
+my $limit = $input->param('recentacqui');
 
 my @branches;
 my @select_branch;
 my %select_branches;
-my $branches = getallbranches();
+my $branches = GetBranches();
 my @branchloop;
-foreach my $thisbranch (keys %$branches) {
-        my $selected = 1 if (C4::Context->userenv && ($thisbranch eq C4::Context->userenv->{branch}));
-        my %row =(value => $thisbranch,
-                                selected => $selected,
-                                branchname => $branches->{$thisbranch}->{'branchname'},
-                        );
-        push @branchloop, \%row;
+foreach my $thisbranch ( keys %$branches ) {
+    my $selected = 1
+      if ( C4::Context->userenv
+        && ( $thisbranch eq C4::Context->userenv->{branch} ) );
+    my %row = (
+        value      => $thisbranch,
+        selected   => $selected,
+        branchname => $branches->{$thisbranch}->{'branchname'},
+    );
+    push @branchloop, \%row;
 }
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-main.tmpl",
+        type            => "opac",
+        query           => $input,
+        authnotrequired => 1,
+        flagsrequired   => { borrow => 1 },
+    }
+);
 
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "opac-main.tmpl",
-                            type => "opac",
-                            query => $input,
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                        });
-my $borrower = getmember('',$borrowernumber);
-my @options;
-my $counter=0;
-foreach my $language (getalllanguages()) {
-       next if $language eq 'images';
-       next if $language eq 'CVS';
-       next if $language=~ /png$/;
-       next if $language=~ /css$/;
-       my $selected='0';
-#                            next if $currently_selected_languages->{$language};
-       push @options, { language => $language, counter => $counter };
-       $counter++;
-}
-my $languages_count = @options;
-if($languages_count > 1){
-               $template->param(languages => \@options);
+if($limit) {
+    my $recentacquiloop = GetRecentAcqui($limit);
+    warn Data::Dumper::Dumper($recentacquiloop);
+    $template->param(
+        recentacquiloop => $recentacquiloop,
+    );
 }
 
-my $branchinfo = getbranchinfo();
-my @loop_data =();
-foreach my $branch (@$branchinfo) {
-        my %row =();
-        $row{'branch_name'} = $branch->{'branchname'};
-        $row{'branch_hours'} = $branch->{'branchhours'};
-        $row{'branch_hours'} =~ s^\n^<br />^g;
-        push (@loop_data, \%row);
-    }
+my $borrower = GetMember( '', $borrowernumber );
+my @languages;
+my $counter = 0;
+my $langavail = getTranslatedLanguages('opac');
+foreach my $language ( @$langavail ) {
+    #   next if $currently_selected_languages->{$language};
+       #   FIXME: could incorporate language_name and language_locale_name for better display
+    push @languages, { language => $language->{'language_code'}, counter => $counter };
+    $counter++;
+}
 
-sub getbranchinfo {
-        my $dbh = C4::Context->dbh;
-        my $sth;
-        $sth = $dbh->prepare("Select * from branches order by branchcode");
-        $sth->execute();
-    
-        my @results;
-        while(my $data = $sth->fetchrow_hashref) {
-                   push(@results, $data);
-               }
-        $sth->finish;
-        return \@results;
+# Template params
+if ( $counter > 1 ) {
+    $template->param(languages => \@languages) if C4::Context->preference('opaclanguagesdisplay');
 }
 
+$template->param(
+    branchloop           => \@branchloop,
+    textmessaging        => $borrower->{textmessaging},
+    opaclanguagesdisplay => 0,
+);
+
+# display news
+# use cookie setting for language, bug default to syspref if it's not set
+my $news_lang = $input->cookie('KohaOpacLanguage') || C4::Context->preference('opaclanguages');
+my  $all_koha_news  = &GetNewsToDisplay( $news_lang );
+my $koha_news_count = scalar @$all_koha_news;
 
-$template->param(              suggestion => C4::Context->preference("suggestion"),
-                               virtualshelves => C4::Context->preference("virtualshelves"),
-                               textmessaging => $borrower->{textmessaging},
-                               opaclargeimage => C4::Context->preference("opaclargeimage"),
-                               LibraryName => C4::Context->preference("LibraryName"),
-                               OpacNav => C4::Context->preference("OpacNav"),
-                               opaccredits => C4::Context->preference("opaccredits"),
-                               opacreadinghistory => C4::Context->preference("opacreadinghistory"),
-                               opacsmallimage => C4::Context->preference("opacsmallimage"),
-                               opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
-                               opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
-                               opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
-                                branches => \@loop_data,
+$template->param(
+    koha_news       => $all_koha_news,
+    koha_news_count => $koha_news_count
 );
 
-$template->param('Disable_Dictionary'=>C4::Context->preference("Disable_Dictionary")) if (C4::Context->preference("Disable_Dictionary"));
+$template->param(
+    'Disable_Dictionary' => C4::Context->preference("Disable_Dictionary") )
+  if ( C4::Context->preference("Disable_Dictionary") );
 
 output_html_with_http_headers $input, $cookie, $template->output;
index bf13923..f7f3846 100755 (executable)
@@ -22,71 +22,83 @@ use strict;
 require Exporter;
 use CGI;
 
-use C4::Auth;         # checkauth, getborrowernumber.
+use C4::Auth;    # checkauth, getborrowernumber.
 use C4::Context;
 use Digest::MD5 qw(md5_base64);
 use C4::Circulation::Circ2;
-use HTML::Template;
+
 use C4::Interface::CGI::Output;
 
 my $query = new CGI;
-my $dbh = C4::Context->dbh;
+my $dbh   = C4::Context->dbh;
 
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-passwd.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-passwd.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-my $sth = $dbh->prepare("UPDATE borrowers SET password = ? WHERE borrowernumber=?");
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
+my $sth =
+  $dbh->prepare("UPDATE borrowers SET password = ? WHERE borrowernumber=?");
 
-if ( $query->param('Oldkey') && $query->param('Newkey') && $query->param('Confirm') ){
-       if ( goodkey($dbh,$borrowernumber, $query->param('Oldkey')) ){
-               if ( $query->param('Newkey') eq $query->param('Confirm') &&
-                       length($query->param('Confirm')) > 5 ){ # Record password
-                       my $clave = md5_base64($query->param('Newkey'));
-                       $sth->execute($clave,$borrowernumber);
-                       $template->param('password_updated' => '1');
-                       $template->param('borrowernumber' => $borrowernumber);
-               }elsif ( $query->param('Newkey') ne $query->param('Confirm') ){
-                       $template->param('Ask_data' => '1');
-                       $template->param('Error_messages' => '1');
-                       $template->param('PassMismatch' => '1');
-               }elsif (length($query->param('Confirm')) <= 5 ){
-                       $template->param('Ask_data' => '1');
-                       $template->param('Error_messages' => '1');
-                       $template->param('ShortPass' => '1');
-               }else{
-                       $template->param('Error_messages' => '1');
-               } 
-       }else{
-               $template->param('Ask_data' => '1');
-               $template->param('Error_messages' => '1');
-               $template->param('WrongPass' => '1');
-       }
-}else {
-# Called Empty, Ask for data.
-       $template->param('Ask_data' => '1');
+if (   $query->param('Oldkey')
+    && $query->param('Newkey')
+    && $query->param('Confirm') )
+{
+    if ( goodkey( $dbh, $borrowernumber, $query->param('Oldkey') ) ) {
+        if ( $query->param('Newkey') eq $query->param('Confirm')
+            && length( $query->param('Confirm') ) > 5 )
+        {    # Record password
+            my $clave = md5_base64( $query->param('Newkey') );
+            $sth->execute( $clave, $borrowernumber );
+            $template->param( 'password_updated' => '1' );
+            $template->param( 'borrowernumber'   => $borrowernumber );
+        }
+        elsif ( $query->param('Newkey') ne $query->param('Confirm') ) {
+            $template->param( 'Ask_data'       => '1' );
+            $template->param( 'Error_messages' => '1' );
+            $template->param( 'PassMismatch'   => '1' );
+        }
+        elsif ( length( $query->param('Confirm') ) <= 5 ) {
+            $template->param( 'Ask_data'       => '1' );
+            $template->param( 'Error_messages' => '1' );
+            $template->param( 'ShortPass'      => '1' );
+        }
+        else {
+            $template->param( 'Error_messages' => '1' );
+        }
+    }
+    else {
+        $template->param( 'Ask_data'       => '1' );
+        $template->param( 'Error_messages' => '1' );
+        $template->param( 'WrongPass'      => '1' );
+    }
 }
+else {
 
-$template->param(LibraryName => C4::Context->preference("LibraryName"),
-);
+    # Called Empty, Ask for data.
+    $template->param( 'Ask_data' => '1' );
+}
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
-
 sub goodkey {
-my ($dbh, $borrowernumber, $key) = @_;
+    my ( $dbh, $borrowernumber, $key ) = @_;
 
-       my $sth=$dbh->prepare("SELECT password FROM borrowers WHERE borrowernumber=?");
-       $sth->execute($borrowernumber);
-       if ($sth->rows){
-               my ($md5password) = $sth->fetchrow;
-               if (md5_base64($key) eq $md5password) { return 1; } else { return 0; }
-       }else{ return 0; }
+    my $sth =
+      $dbh->prepare("SELECT password FROM borrowers WHERE borrowernumber=?");
+    $sth->execute($borrowernumber);
+    if ( $sth->rows ) {
+        my ($md5password) = $sth->fetchrow;
+        if ( md5_base64($key) eq $md5password ) { return 1; }
+        else { return 0; }
+    }
+    else { return 0; }
 }
index ba34745..a316e3b 100755 (executable)
@@ -1,4 +1,22 @@
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+# $Id$
+
 use strict;
 require Exporter;
 use CGI;
@@ -8,48 +26,50 @@ use C4::Koha;
 use C4::Circulation::Circ2;
 use C4::Date;
 use C4::Members;
-use HTML::Template;
+
 use C4::Interface::CGI::Output;
 
 my $query = new CGI;
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-readingrecord.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-readingrecord.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
 $template->param($borr);
 
 # get the record
-my $order=$query->param('order');
-my $order2=$order;
-if ($order2 eq ''){
-  $order2="date_due desc";
-  $template->param(orderbydate => 1);
+my $order  = $query->param('order');
+my $order2 = $order;
+if ( $order2 eq '' ) {
+    $order2 = "date_due desc";
+    $template->param( orderbydate => 1 );
 }
 
-if($order2 eq 'title'){
-       $template->param(orderbytitle => 1);
-       }
+if ( $order2 eq 'title' ) {
+    $template->param( orderbytitle => 1 );
+}
 
-if($order2 eq 'author'){
-       $template->param(orderbyauthor => 1);
+if ( $order2 eq 'author' ) {
+    $template->param( orderbyauthor => 1 );
 }
 
-my $limit=$query->param('limit');
-if ($limit eq 'full'){
-  $limit=0;
-} else {
-  $limit=50;
+my $limit = $query->param('limit');
+if ( $limit eq 'full' ) {
+    $limit = 0;
 }
-my ($count,$issues)=allissues($borrowernumber,$order2,$limit);
+else {
+    $limit = 50;
+}
+my ( $count, $issues ) = allissues( $borrowernumber, $order2, $limit );
 
 # add the row parity
 #my $num = 0;
@@ -61,28 +81,28 @@ my ($count,$issues)=allissues($borrowernumber,$order2,$limit);
 
 my @loop_reading;
 
-for (my $i=0;$i<$count;$i++){
-       my %line;
-       if($i%2){
-               $line{'toggle'} = 1;
-       }
-       $line{biblionumber}=$issues->[$i]->{'biblionumber'};
-       $line{title}=$issues->[$i]->{'title'};
-       $line{author}=$issues->[$i]->{'author'};
-       $line{classification} = $issues->[$i]->{'classification'};
-       $line{date_due}=format_date($issues->[$i]->{'date_due'});
-       $line{returndate}=format_date($issues->[$i]->{'returndate'});
-       $line{volumeddesc}=$issues->[$i]->{'volumeddesc'};
-       $line{counter} = $i + 1;
-       push(@loop_reading,\%line);
+for ( my $i = 0 ; $i < $count ; $i++ ) {
+    my %line;
+    if ( $i % 2 ) {
+        $line{'toggle'} = 1;
+    }
+    $line{biblionumber}   = $issues->[$i]->{'biblionumber'};
+    $line{title}          = $issues->[$i]->{'title'};
+    $line{author}         = $issues->[$i]->{'author'};
+    $line{classification} = $issues->[$i]->{'classification'};
+    $line{date_due}       = format_date( $issues->[$i]->{'date_due'} );
+    $line{returndate}     = format_date( $issues->[$i]->{'returndate'} );
+    $line{volumeddesc}    = $issues->[$i]->{'volumeddesc'};
+    $line{counter}        = $i + 1;
+    push( @loop_reading, \%line );
 }
 
-$template->param(count => $count,
-                               READING_RECORD => \@loop_reading,
-                               limit => $limit,
-                               showfulllink => ($count > 50),          
+$template->param(
+    count          => $count,
+    READING_RECORD => \@loop_reading,
+    limit          => $limit,
+    showfulllink   => ( $count > 50 ),
 );
 
-
 output_html_with_http_headers $query, $cookie, $template->output;
 
index 4a4e3af..43fc99d 100755 (executable)
@@ -9,17 +9,15 @@ use C4::Circulation::Circ2;
 
 my $query = new CGI;
 
-my $itemnumber = $query->param('item');
-my $borrowernumber = $query->param("bornum");
-
-
+my $itemnumber     = $query->param('item');
+my $borrowernumber = $query->param("borrowernumber");
 
 my %env;
-my $status = renewstatus(\%env,$borrowernumber,$itemnumber);
-if ($status == 1){
-    renewbook(\%env,$borrowernumber,$itemnumber);
+my $status = renewstatus( \%env, $borrowernumber, $itemnumber );
+if ( $status == 1 ) {
+    renewbook( \%env, $borrowernumber, $itemnumber );
 }
 
-if ($query->param('from') eq 'opac_user') {
+if ( $query->param('from') eq 'opac_user' ) {
     print $query->redirect("/cgi-bin/koha/opac-user.pl");
 }
index 356f658..1626fdc 100755 (executable)
 #!/usr/bin/perl
-# NOTE: This file uses standard 8-character tabs
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
 
 use strict;
 require Exporter;
 use CGI;
-
 use C4::Biblio;
-use C4::Auth;         # checkauth, getborrowernumber.
+use C4::Auth;    # checkauth, getborrowernumber.
 use C4::Koha;
 use C4::Circulation::Circ2;
 use C4::Reserves2;
 use C4::Interface::CGI::Output;
-use HTML::Template;
 use C4::Date;
 use C4::Context;
+use C4::Branch; # GetBranches
 
 my $MAXIMUM_NUMBER_OF_RESERVES = C4::Context->preference("maxreserves");
 
 my $query = new CGI;
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "opac-reserve.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-reserve.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-# my @bordat;
-# $bordat[0] = $borr;
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
 # get biblionumber.....
-my $biblionumber = $query->param('bib');
+my $biblionumber = $query->param('biblionumber');
 
-my $bibdata = bibdata($biblionumber);
- $template->param($bibdata);
- $template->param(biblionumber => $biblionumber);
+my $bibdata = GetBiblioData($biblionumber);
+$template->param($bibdata);
+$template->param( biblionumber => $biblionumber );
 
 # get the rank number....
-my ($rank,$reserves) = FindReserves($biblionumber,'');
-$template->param(reservecount => $rank);
+my ( $rank, $reserves ) = FindReserves( $biblionumber, '' );
+$template->param( reservecount => $rank );
 
 foreach my $res (@$reserves) {
-    if ($res->{'found'} eq 'W') {
-       $rank--;
+    if ( $res->{'found'} eq 'W' ) {
+        $rank--;
     }
 }
 
 $rank++;
-$template->param(rank => $rank);
+$template->param( rank => $rank );
 
 # pass the pickup branch along....
 my $branch = $query->param('branch');
-$template->param(branch => $branch);
+$template->param( branch => $branch );
 
 my $branches = GetBranches();
+
 # make sure it's a real branch
-if (!$branches->{$branch}) {
-$branch='';
+if ( !$branches->{$branch} ) {
+    $branch = '';
 }
-$template->param(branchname => $branches->{$branch}->{'branchname'});
+$template->param( branchname => $branches->{$branch}->{'branchname'} );
 
 # make branch selection options...
-#my $branchoptions = '';
 my @branches;
 my @select_branch;
 my %select_branches;
 
 my @CGIbranchlooparray;
 
-foreach my $branch (keys %$branches) {
-       if ($branch) {
-               my %line;
-               $line{branch} = $branches->{$branch}->{'branchname'};
-               $line{value} = $branch;
-               push @CGIbranchlooparray, \%line;
-       }
+foreach my $branch ( keys %$branches ) {
+    if ($branch) {
+        my %line;
+        $line{branch} = $branches->{$branch}->{'branchname'};
+        $line{value}  = $branch;
+        push @CGIbranchlooparray, \%line;
+    }
 }
-@CGIbranchlooparray = sort {$a->{branch} cmp $b->{branch}} @CGIbranchlooparray;
+@CGIbranchlooparray =
+  sort { $a->{branch} cmp $b->{branch} } @CGIbranchlooparray;
 my $CGIbranchloop = \@CGIbranchlooparray;
-$template->param( CGIbranch => $CGIbranchloop);
+$template->param( CGIbranch => $CGIbranchloop );
 
 #### THIS IS A BIT OF A HACK BECAUSE THE BIBLIOITEMS DATA IS A LITTLE MESSED UP!
 # get the itemtype data....
-my @items = ItemInfo(undef, $biblionumber, 'opac');
+my @items = GetItemInfosOf($biblionumber);
 
 #######################################################
 # old version, add so that old templates still work
 my %types_old;
 foreach my $itm (@items) {
     my $ity = $itm->{'itemtype'};
-    unless ($types_old {$ity}) {
-       $types_old{$ity}->{'itemtype'} = $ity;
-       $types_old{$ity}->{'branchinfo'}->{$itm->{'branchcode'}} = 1;
-       $types_old{$ity}->{'description'} = $itm->{'description'};
-    } else {
-       $types_old{$ity}->{'branchinfo'}->{$itm->{'branchcode'}} ++;
+    unless ( $types_old{$ity} ) {
+        $types_old{$ity}->{'itemtype'} = $ity;
+        $types_old{$ity}->{'branchinfo'}->{ $itm->{'branchcode'} } = 1;
+        $types_old{$ity}->{'description'} = $itm->{'description'};
+    }
+    else {
+        $types_old{$ity}->{'branchinfo'}->{ $itm->{'branchcode'} }++;
     }
 }
 
-foreach my $type (values %types_old) {
+foreach my $type ( values %types_old ) {
     my $copies = "";
-    foreach my $bc (keys %{$type->{'branchinfo'}}) {
-       $copies .= $branches->{$bc}->{'branchname'}."(".$type->{'branchinfo'}->{$bc}.")";
+    foreach my $bc ( keys %{ $type->{'branchinfo'} } ) {
+        $copies .=
+            $branches->{$bc}->{'branchname'} . "("
+          . $type->{'branchinfo'}->{$bc} . ")";
     }
     $type->{'copies'} = $copies;
 }
@@ -120,165 +137,184 @@ foreach my $itm (@items) {
 }
 @items = @temp;
 my $itemcount = @items;
-$template->param(itemcount => $itemcount);
+$template->param( itemcount => $itemcount );
 
 my %types;
 my %itemtypes;
 my @duedates;
 foreach my $itm (@items) {
-    push @duedates, {date_due => format_date($itm->{'date_due'})} if defined $itm->{'date_due'};
-    $itm->{$itm->{'publictype'}} = 1;
+    push @duedates, { date_due => format_date( $itm->{'date_due'} ) }
+      if defined $itm->{'date_due'};
+    $itm->{ $itm->{'publictype'} } = 1;
+
     # FIXME CalcReserveFee is supposed to be internal-use-only
-    my $fee  = CalcReserveFee(undef, $borrowernumber, $itm->{'biblionumber'},'a',($itm->{'biblioitemnumber'}));
+    my $fee = CalcReserveFee( undef, $borrowernumber, $itm->{'biblionumber'},
+        'a', ( $itm->{'biblioitemnumber'} ) );
     $fee = sprintf "%.02f", $fee;
     $itm->{'reservefee'} = $fee;
     my $pty = $itm->{'publictype'};
-    $itemtypes{$itm->{'itemtype'}} = $itm;
-    unless ($types {$pty}) {
-       $types{$pty}->{'count'} = 1;
-       $types{$pty}->{$itm->{'itemtype'}} = 1;
-       push @{$types{$pty}->{'items'}}, $itm;
-    } else {
-       unless ($types{$pty}->{$itm->{'itemtype'}}) {
-           $types{$pty}->{'count'}++;
-           $types{$pty}->{$itm->{'itemtype'}} = 1;
-           push @{$types{$pty}->{'items'}}, $itm;
-       }
+    $itemtypes{ $itm->{'itemtype'} } = $itm;
+    unless ( $types{$pty} ) {
+        $types{$pty}->{'count'} = 1;
+        $types{$pty}->{ $itm->{'itemtype'} } = 1;
+        push @{ $types{$pty}->{'items'} }, $itm;
+    }
+    else {
+        unless ( $types{$pty}->{ $itm->{'itemtype'} } ) {
+            $types{$pty}->{'count'}++;
+            $types{$pty}->{ $itm->{'itemtype'} } = 1;
+            push @{ $types{$pty}->{'items'} }, $itm;
+        }
     }
 }
 
-
-$template->param(ITEMS => \@duedates);
+$template->param( ITEMS => \@duedates );
 
 my $width = keys %types;
-my @publictypes = sort {$b->{'count'} <=> $a->{'count'}} values %types;
+my @publictypes = sort { $b->{'count'} <=> $a->{'count'} } values %types;
 my $typecount;
 foreach my $pt (@publictypes) {
     $typecount += $pt->{'count'};
 }
-$template->param(onlyone => 1) if $typecount == 1;
+$template->param( onlyone => 1 ) if $typecount == 1;
 
 my @typerows;
-for (my $rownum=0;$rownum<$publictypes[0]->{'count'} ;$rownum++) {
+for ( my $rownum = 0 ; $rownum < $publictypes[0]->{'count'} ; $rownum++ ) {
     my @row;
     foreach my $pty (@publictypes) {
-       my @items = @{$pty->{'items'}};
-       push @row, $items[$rownum] if defined $items[$rownum];
+        my @items = @{ $pty->{'items'} };
+        push @row, $items[$rownum] if defined $items[$rownum];
     }
     my $last = @row;
-    $row[$last-1]->{'last'} =1 if $last == $width;
-    my $fill = ($width - $last)*2;
+    $row[ $last - 1 ]->{'last'} = 1 if $last == $width;
+    my $fill = ( $width - $last ) * 2;
     $fill-- if $fill;
-    push @typerows, {ROW => \@row, fill => $fill};
+    push @typerows, { ROW => \@row, fill => $fill };
 }
-$template->param(TYPE_ROWS => \@typerows);
-$width = 2*$width -1;
-$template->param(totalwidth => 2*$width-1,
-);
+$template->param( TYPE_ROWS => \@typerows );
+$width = 2 * $width - 1;
+$template->param( totalwidth => 2 * $width - 1, );
 
-if ($query->param('item_types_selected')) {
-       # this is what happens after the itemtypes have been selected. Stage 2
-       my @itemtypes = $query->param('itemtype');
-       my $fee = 0;
-       my $proceed = 0;
-       if (@itemtypes) {
-               my %newtypes;
-               foreach my $itmtype (@itemtypes) {
-               $newtypes{$itmtype} = $itemtypes{$itmtype};
-               }
-               my @types = values %newtypes;
-               $template->param(TYPES => \@types);
-               foreach my $type (@itemtypes) {
-               my @reqbibs;
-               foreach my $item (@items) {
-                       if ($item->{'itemtype'} eq $type) {
-                       push @reqbibs, $item->{'biblioitemnumber'};
-                       }
-               }
-               $fee += CalcReserveFee(undef,$borrowernumber,$biblionumber,'o',\@reqbibs);
-               }
-               $proceed = 1;
-       } elsif ($query->param('all')) {
-               $template->param(all => 1);
-               $fee = 1;
-               $proceed = 1;
-       }
-       if ($proceed && $branch) {
-               $fee = sprintf "%.02f", $fee;
-               $template->param(fee => $fee,istherefee => $fee>0?1:0);
-               $template->param(item_types_selected => 1);
-               warn "Branch is ==$branch==";
-               $template->param(no_branch_selected => 1) unless ($branch!='');
-       } else {
-               $template->param(message => 1);
-               $template->param(no_items_selected => 1) unless ($proceed);
-               $template->param(no_branch_selected => 1) unless ($branch);
-               warn "Branch is ==$branch==";
-       }
-} elsif ($query->param('place_reserve')) {
-       # here we actually do the reserveration. Stage 3.
-       my $title = $bibdata->{'title'};
-       my @itemtypes = $query->param('itemtype');
-       foreach my $type (@itemtypes) {
-               my @reqbibs;
-               foreach my $item (@items) {
-               if ($item->{'itemtype'} eq $type) {
-                       push @reqbibs, $item->{'biblioitemnumber'};
-               }
-               }
-               CreateReserve(undef,$branch,$borrowernumber,$biblionumber,'o',\@reqbibs,$rank,'',$title);
-       }
-       if ($query->param('all')) {
-               CreateReserve(undef,$branch,$borrowernumber,$biblionumber,'a', undef, $rank,'',$title);
-       }
-       print $query->redirect("/cgi-bin/koha/opac-user.pl");
-} else {
-       # Here we check that the borrower can actually make reserves Stage 1.
-       my $noreserves = 0;
-       my $maxoutstanding = C4::Context->preference("maxoutstanding");
-       $template->param(noreserve => 1) unless $maxoutstanding;
-       if ($borr->{'amountoutstanding'} > $maxoutstanding) {
-               my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
-               $template->param(message => 1);
-               $noreserves = 1;
-               $template->param(too_much_oweing => $amount);
-       }
-       if ($borr->{gonenoaddress} eq 1) {
-               $noreserves = 1;
-               $template->param(message => 1,
-                                               GNA => 1);
-       }
-       if ($borr->{lost} eq 1) {
-               $noreserves = 1;
-               $template->param(message => 1,
-                                               lost => 1);
-       }
-       if ($borr->{debarred} eq 1) {
-               $noreserves = 1;
-               $template->param(message => 1,
-                                               debarred => 1);
-       }
-       my ($resnum, $reserves) = FindReserves('', $borrowernumber);
-       $template->param(RESERVES => $reserves);
-       if ($resnum >= $MAXIMUM_NUMBER_OF_RESERVES) {
-               $template->param(message => 1);
-               $noreserves = 1;
-               $template->param(too_many_reserves => $resnum);
-       }
-       foreach my $res (@$reserves) {
-               if ($res->{'biblionumber'} == $biblionumber) {
-               $template->param(message => 1);
-               $noreserves = 1;
-               $template->param(already_reserved => 1);
+if ( $query->param('item_types_selected') ) {
+
+    # this is what happens after the itemtypes have been selected. Stage 2
+    my @itemtypes = $query->param('itemtype');
+    my $fee       = 0;
+    my $proceed   = 0;
+    if (@itemtypes) {
+        my %newtypes;
+        foreach my $itmtype (@itemtypes) {
+            $newtypes{$itmtype} = $itemtypes{$itmtype};
+        }
+        my @types = values %newtypes;
+        $template->param( TYPES => \@types );
+        foreach my $type (@itemtypes) {
+            my @reqbibs;
+            foreach my $item (@items) {
+                if ( $item->{'itemtype'} eq $type ) {
+                    push @reqbibs, $item->{'biblioitemnumber'};
+                }
+            }
+            $fee +=
+              CalcReserveFee( undef, $borrowernumber, $biblionumber, 'o',
+                \@reqbibs );
+        }
+        $proceed = 1;
+    }
+    elsif ( $query->param('all') ) {
+        $template->param( all => 1 );
+        # No idea why fee would be set to 1 ... it's supposed to be a monetary value, not a flag
+               # -- JF
+               #$fee = 1;
+               $proceed = 1;
+    }
+    if ( $proceed && $branch ) {
+        $fee = sprintf "%.02f", $fee;
+               if ($fee > 1) {
+        $template->param( fee => $fee, istherefee => $fee > 0 ? 1 : 0 );
                }
-       }
-       unless ($noreserves) {
-               $template->param(TYPES => \@types_old);
-               $template->param(select_item_types => 1);
-       }
+        $template->param( item_types_selected => 1 );
+        $template->param( no_branch_selected => 1 ) unless ( $branch != '' );
+    }
+    else {
+        $template->param( message            => 1 );
+        $template->param( no_items_selected  => 1 ) unless ($proceed);
+        $template->param( no_branch_selected => 1 ) unless ($branch);
+    }
+}
+elsif ( $query->param('place_reserve') ) {
+
+    # here we actually do the reserveration. Stage 3.
+    my $title     = $bibdata->{'title'};
+    my @itemtypes = $query->param('itemtype');
+    foreach my $type (@itemtypes) {
+        my @reqbibs;
+        foreach my $item (@items) {
+            if ( $item->{'itemtype'} eq $type ) {
+                push @reqbibs, $item->{'biblioitemnumber'};
+            }
+        }
+        CreateReserve( undef, $branch, $borrowernumber, $biblionumber, 'o',
+            \@reqbibs, $rank, '', $title );
+    }
+    if ( $query->param('all') ) {
+        CreateReserve( undef, $branch, $borrowernumber, $biblionumber, 'a',
+            undef, $rank, '', $title );
+    }
+    print $query->redirect("/cgi-bin/koha/opac-user.pl");
 }
+else {
 
-# check that you can actually make the reserve.
+    # Here we check that the borrower can actually make reserves Stage 1.
+    my $noreserves     = 0;
+    my $maxoutstanding = C4::Context->preference("maxoutstanding");
+    $template->param( noreserve => 1 ) unless $maxoutstanding;
+    if ( $borr->{'amountoutstanding'} > $maxoutstanding ) {
+        my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
+        $template->param( message => 1 );
+        $noreserves = 1;
+        $template->param( too_much_oweing => $amount );
+    }
+    if ( $borr->{gonenoaddress} eq 1 ) {
+        $noreserves = 1;
+        $template->param(
+            message => 1,
+            GNA     => 1
+        );
+    }
+    if ( $borr->{lost} eq 1 ) {
+        $noreserves = 1;
+        $template->param(
+            message => 1,
+            lost    => 1
+        );
+    }
+    if ( $borr->{debarred} eq 1 ) {
+        $noreserves = 1;
+        $template->param(
+            message  => 1,
+            debarred => 1
+        );
+    }
+    my ( $resnum, $reserves ) = FindReserves( '', $borrowernumber );
+    $template->param( RESERVES => $reserves );
+    if ( $resnum >= $MAXIMUM_NUMBER_OF_RESERVES ) {
+        $template->param( message => 1 );
+        $noreserves = 1;
+        $template->param( too_many_reserves => $resnum );
+    }
+    foreach my $res (@$reserves) {
+        if ( $res->{'biblionumber'} == $biblionumber ) {
+            $template->param( message => 1 );
+            $noreserves = 1;
+            $template->param( already_reserved => 1 );
+        }
+    }
+    unless ($noreserves) {
+        $template->param( TYPES             => \@types_old );
+        $template->param( select_item_types => 1 );
+    }
+}
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
index 6d238ca..389175b 100755 (executable)
 use strict;
 require Exporter;
 use CGI;
-
 use C4::Auth;
 use C4::Koha;
-use HTML::Template;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 use C4::Review;
@@ -38,17 +36,11 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
         template_name   => "opac-review.tmpl",
         query           => $query,
         type            => "opac",
-        authnotrequired => 0,
-        flagsrequired   => { borrow => 1 },
-        debug           => 1,
+        authnotrequired => 1,
     }
 );
 
-# get borrower information ....
-# my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-# $template->param($borr);
-
-my $biblio = bibdata( $biblionumber, 'opac' );
+my $biblio = GetBiblioData( $biblionumber, 'opac' );
 
 my $savedreview = getreview( $biblionumber, $borrowernumber );
 if ( $type eq 'save' ) {
@@ -69,7 +61,7 @@ $template->param(
     'borrowernumber' => $borrowernumber,
     'type'           => $type,
     'review'         => $reviewdata,
-    'title'          => $biblio->{'title'}
+    'title'          => $biblio->{'title'},
 );
 
 # get the record
index 0b17e49..f11c710 100755 (executable)
 #!/usr/bin/perl
-use strict;
-require Exporter;
 
-use C4::Auth;
-use C4::Interface::CGI::Output;
+# Script to perform searching
+# For documentation try 'perldoc /path/to/search'
+#
+# $Header$
+#
+# Copyright 2006 LibLime
+#
+# This file is part of Koha
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+=head1 NAME
+
+search - a search script for finding records in a Koha system (Version 2.4)
+
+=head1 OVERVIEW
+
+This script contains a demonstration of a new search API for Koha 2.4. It is
+designed to be simple to use and configure, yet capable of performing feats
+like stemming, field weighting, relevance ranking, support for multiple 
+query language formats (CCL, CQL, PQF), full or nearly full support for the
+bib1 attribute set, extended attribute sets defined in Zebra profiles, access
+to the full range of Z39.50 query options, federated searches on Z39.50
+targets, etc.
+
+I believe the API as represented in this script is mostly sound, even if the
+individual functions in Search.pm and Koha.pm need to be cleaned up. Of course,
+you are free to disagree :-)
+
+I will attempt to describe what is happening at each part of this script.
+-- JF
+
+=head2 INTRO
+
+This script performs two functions:
+
+=over 
+
+=item 1. interacts with Koha to retrieve and display the results of a search
+
+=item 2. loads the advanced search page
+
+=back
+
+These two functions share many of the same variables and modules, so the first
+task is to load what they have in common and determine which template to use.
+Once determined, proceed to only load the variables and procedures necessary
+for that function.
+
+=head2 THE ADVANCED SEARCH PAGE
+
+If we're loading the advanced search page this script will call a number of
+display* routines which populate objects that are sent to the template for 
+display of things like search indexes, languages, search limits, branches,
+etc. These are not stored in the template for two reasons:
+
+=over
+
+=item 1. Efficiency - we have more control over objects inside the script, and it's possible to not duplicate things like indexes (if the search indexes were stored in the template they would need to be repeated)
+
+=item 2. Customization - if these elements were moved to the sql database it would allow a simple librarian to determine which fields to display on the page without editing any html (also how the fields should behave when being searched).
+
+=back
+
+However, they create one problem : the strings aren't translated. I have an idea
+for how to do this that I will purusue soon.
+
+=head2 PERFORMING A SEARCH
+
+If we're performing a search, this script  performs three primary
+operations:
+
+=over 
+
+=item 1. builds query strings (yes, plural)
+
+=item 2. perform the search and return the results array
+
+=item 3. build the HTML for output to the template
+
+=back
+
+There are several additional secondary functions performed that I will
+not cover in detail.
+
+=head3 1. Building Query Strings
+    
+There are several types of queries needed in the process of search and retrieve:
+
+=over
+
+=item 1 Koha query - the query that is passed to Zebra
+
+This is the most complex query that needs to be built.The original design goal was to use a custom CCL2PQF query parser to translate an incoming CCL query into a multi-leaf query to pass to Zebra. It needs to be multi-leaf to allow field weighting, koha-specific relevance ranking, and stemming. When I have a chance I'll try to flesh out this section to better explain.
+
+This query incorporates query profiles that aren't compatible with non-Zebra Z39.50 targets to acomplish the field weighting and relevance ranking.
+
+=item 2 Federated query - the query that is passed to other Z39.50 targets
+
+This query is just the user's query expressed in CCL CQL, or PQF for passing to a non-zebra Z39.50 target (one that doesn't support the extended profile that Zebra does).
+
+=item 3 Search description - passed to the template / saved for future refinements of the query (by user)
+
+This is a simple string that completely expresses the query in a way that can be parsed by Koha for future refinements of the query or as a part of a history feature. It differs from the human search description in several ways:
+
+1. it does not contain commas or = signs
+2. 
+
+=item 4 Human search description - what the user sees in the search_desc area
+
+This is a simple string nearly identical to the Search description, but more human readable. It will contain = signs or commas, etc.
+
+=back
+
+=head3 2. Perform the Search
+
+This section takes the query strings and performs searches on the named servers, including the Koha Zebra server, stores the results in a deeply nested object, builds 'faceted results', and returns these objects.
+
+=head3 3. Build HTML
+
+The final major section of this script takes the objects collected thusfar and builds the HTML for output to the template and user.
+
+=head3 Additional Notes
+
+Not yet completed...
+
+=cut
+
+use strict;    # always use
+
+#use warnings;        # use only for development
+
+## STEP 1. Load things that are used in both search page and
+# results page and decide which template to load, operations
+# to perform, etc.
+## load Koha modules
 use C4::Context;
-use CGI;
-use C4::Database;
-use HTML::Template;
-use C4::SearchMarc;
-use C4::Acquisition;
-use C4::Biblio;
+use C4::Interface::CGI::Output;
+use C4::Auth;
+use C4::Search;
+use C4::Languages; # getAllLanguages
 use C4::Koha;
+use C4::Branch; # GetBranches
+use POSIX qw(ceil floor);
 
-my @spsuggest; # the array for holding suggestions
-my $suggest;   # a flag to be set (if there are suggestions it's 1)
-my $firstbiblionumber; # needed for directly sending user to first item
-# use C4::Search;
-my $totalresults;
-
-my $itemtypelist;
-my $brancheslist;
-my $categorylist;
-my $subcategorylist;
-my $mediatypelist;
-# added by Gavin 
-my $totalresults;
-
-my $dbh=C4::Context->dbh;
-my $sth=$dbh->prepare("select description,itemtype from itemtypes order by description");
-$sth->execute;
-while (my ($description,$itemtype) = $sth->fetchrow) {
-    $itemtypelist.="<option value=\"$itemtype\">$description</option>\n";
-}
-my $sth=$dbh->prepare("select description,subcategorycode from subcategorytable order by description");
-$sth->execute;
-while (my ($description,$subcategorycode) = $sth->fetchrow) {
-    $subcategorylist.="<option value=\"$subcategorycode\">$description</option>\n";
+# create a new CGI object
+# not sure undef_params option is working, need to test
+use CGI qw('-no_undef_params');
+my $cgi = new CGI;
+
+my ( $template, $borrowernumber, $cookie );
+
+# decide which template to use
+my $template_name;
+my @params = $cgi->param("limit");
+if ( ( @params > 1 ) || ( $cgi->param("q") ) ) {
+
+    $template_name = 'opac-results.tmpl';
 }
-my $sth=$dbh->prepare("select description,mediatypecode from mediatypetable order by description");
-$sth->execute;
-while (my ($description,$mediatypecode) = $sth->fetchrow) {
-    $mediatypelist.="<option value=\"$mediatypecode\">$description</option>\n";
+else {
+
+    $template_name = 'opac-advsearch.tmpl';
 }
-my $sth=$dbh->prepare("select description,categorycode from categorytable order by description");
-$sth->execute;
-while (my ($description,$categorycode) = $sth->fetchrow) {
-    $categorylist .= '<input type="radio" name="categorylist" value="'.$categorycode.'">'.$description.'<br>';
+
+# load the template
+( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => $template_name,
+        query           => $cgi,
+        type            => "opac",
+        authnotrequired => 1,
+    }
+);
+
+=head1 BUGS and FIXMEs
+
+There are many, most are documented in the code. The one that
+isn't fully documented, but referred to is the need for a full
+query parser.
+
+=cut
+
+## URI Re-Writing
+# FIXME: URI re-writing should be tested more carefully and may better
+# handled by mod_rewrite or something else. The code below almost works,
+# but doesn't quite handle limits correctly when they are the only
+# param passed -- I'll work on this soon -- JF
+#my $rewrite_flag;
+#my $uri = $cgi->url(-base => 1);
+#my $relative_url = $cgi->url(-relative=>1);
+#$uri.="/".$relative_url."?";
+#warn "URI:$uri";
+#my @cgi_params_list = $cgi->param();
+#my $url_params = $cgi->Vars;
+
+#for my $each_param_set (@cgi_params_list) {
+#    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
+#}
+#warn "New URI:$uri";
+# Only re-write a URI if there are params or if it already hasn't been re-written
+#unless (($cgi->param('r')) || (!$cgi->param()) ) {
+#    print $cgi->redirect(     -uri=>$uri."&r=1",
+#                            -cookie => $cookie);
+#    exit;
+#}
+
+# load the branches
+my $branches = GetBranches();
+my @branch_loop;
+for my $branch_hash ( keys %$branches ) {
+    push @branch_loop,
+      {
+        value      => "branch: $branch_hash",
+        branchname => $branches->{$branch_hash}->{'branchname'},
+      };
 }
-my $sth=$dbh->prepare("select branchname,branchcode from branches order by branchname");
-$sth->execute;
+$template->param( branchloop => \@branch_loop, );
 
-while (my ($branchname,$branchcode) = $sth->fetchrow) {
-    $brancheslist.="<option value=\"$branchcode\">$branchname</option>\n";
+# load the itemtypes (Called Collection Codes in the template -- used for circ rules )
+my $itemtypes = GetItemTypes;
+my @itemtypesloop;
+my $selected = 1;
+my $cnt;
+my $imgdir = getitemtypeimagesrc();
+foreach my $thisitemtype ( sort keys %$itemtypes ) {
+    my %row = (
+        number   => $cnt++,
+        imageurl => $imgdir . "/" . $itemtypes->{$thisitemtype}->{'imageurl'},
+        code     => $thisitemtype,
+        selected => $selected,
+        description => $itemtypes->{$thisitemtype}->{'description'},
+        count5      => $cnt % 5,
+    );
+    $selected = 0 if ($selected);
+    push @itemtypesloop, \%row;
 }
-my $query = new CGI;
-my $op = $query->param("op");
-my $type=$query->param('type');
-my $avail=$query->param('avail');
-my $itemtypesstring=$query->param("itemtypesstring");
-$itemtypesstring =~s/"//g;
-my @itemtypes = split ( /\|/, $itemtypesstring);
-my $branchesstring=$query->param("branchesstring");
-$branchesstring =~s/"//g;
-my @branches = split (/\|/, $branchesstring);
-
-my $startfrom=$query->param('startfrom');
-$startfrom=0 if(!defined $startfrom);
-my ($template, $loggedinuser, $cookie);
-my $resultsperpage;
-my $searchdesc;
-
-if ($op eq "do_search") {
-       my @marclist = $query->param('marclist');
-       my @and_or = $query->param('and_or');
-       my @excluding = $query->param('excluding');
-       my @operator = $query->param('operator');
-       my @value = $query->param('value');
-       my $orderby = $query->param('orderby');
-       my $desc_or_asc = $query->param('desc_or_asc');
-       my $exactsearch = $query->param('exact');
-       for (my $i=0;$i<=$#marclist;$i++) {
-               if ($searchdesc) { # don't put the and_or on the 1st search term
-                       $searchdesc .= $and_or[$i].$excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*").$operator[$i].$value[$i] if ($value[$i]);
-               } else {
-                       $searchdesc = $excluding[$i].($marclist[$i]?$marclist[$i]:"*").$operator[$i].$value[$i] if ($value[$i]);
-                       if ($marclist[$i] eq "biblioitems.isbn") {
-                               $value[$i] =~ s/-//g;
-                       }
-               }
-       }
-  if ($itemtypesstring ne ''){
-    $searchdesc .= 'filtered by itemtypes ';
-    $searchdesc .= join(" ",@itemtypes)
-  }
-
-  if ($branchesstring ne ''){
-    $searchdesc .= ' in branches ';
-    $searchdesc .= join(" ",@branches)
-  }
-  if ($avail ne ''){
-    $searchdesc .= '. Only available items shown.'
-  }
-       $resultsperpage= $query->param('resultsperpage');
-       $resultsperpage = 19 if(!defined $resultsperpage);
-       
-       if ($exactsearch) {
-               foreach (@operator) {
-                       $_='=';
-               }
-       }
-       # builds tag and subfield arrays
-       my @tags;
-
-       foreach my $marc (@marclist) {
-               if ($marc) {
-                       my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,$marc,'');
-                       if ($tag) {
-                               push @tags,$dbh->quote("$tag$subfield");
-                       } else {
-                               push @tags, $dbh->quote(substr($marc,0,4));
-                       }
-               } else {
-                       push @tags, "";
-               }
-       }
-       findseealso($dbh,\@tags);
-    my $sqlstring;
-    my $extratables;
-    if ($itemtypesstring ne ''){
-        $sqlstring = 'and (biblioitems.itemtype IN (';
-        my $itemtypeloop=0;
-        foreach my $itemtype (@itemtypes){
-            if ($itemtype ne ''){
-                if ($itemtypeloop != 0){
-                    $sqlstring .=','
-                }
-                $sqlstring .= '"'.$itemtype.'"';
-                $itemtypeloop++;
-            }
+$template->param( itemtypeloop => \@itemtypesloop );
+
+# # load the itypes (Called item types in the template -- just authorized values for searching)
+# my ($itypecount,@itype_loop) = GetCcodes();
+# $template->param(itypeloop=>\@itype_loop,);
+
+# load the languages ( for switching from one template to another )
+# my @languages_options = displayLanguages($cgi);
+# my $languages_count = @languages_options;
+# if($languages_count > 1){
+#         $template->param(languages => \@languages_options);
+# }
+
+# The following should only be loaded if we're bringing up the advanced search template
+if ( $template_name eq "opac-advsearch.tmpl" ) {
+
+    # load the servers (used for searching -- to do federated searching, etc.)
+    my $primary_servers_loop;    # = displayPrimaryServers();
+    $template->param( outer_servers_loop => $primary_servers_loop, );
+
+    my $secondary_servers_loop;    # = displaySecondaryServers();
+    $template->param( outer_sup_servers_loop => $secondary_servers_loop, );
+
+    # load the limit types (icon-based limits in advanced search page)
+    my $outer_limit_types_loop = displayLimitTypes();
+    $template->param( outer_limit_types_loop => $outer_limit_types_loop, );
+
+    # load the search indexes (what a user can choose to search by)
+    my $indexes = displayIndexes();
+
+    # determine what to display next to the search boxes (ie, boolean option
+    # shouldn't appear on the first one, scan indexes should, adding a new
+    # box should only appear on the last, etc.
+    # FIXME: this stuff should be cleaned up a bit and the html should be turned
+    # into flags for the template -- I'll work on that soon -- JF
+    my @search_boxes_array;
+    my $search_boxes_count = 1;    # should be a syspref
+    for ( my $i = 0 ; $i <= $search_boxes_count ; $i++ ) {
+        my $this_index = [@$indexes];   # clone the data, not just the reference
+             #@$this_index[$i]->{selected} = "selected";
+        if ( $i == 0 ) {
+            push @search_boxes_array,
+              {
+                indexes            => $this_index,
+                search_boxes_label => "<span class='labels'>Search for:</span>",
+                scan_index         =>
+"<input type='checkbox' name='scan' id='scan' value='1'/><label for='scan'>Scan Indexes</label>",
+              };
+
         }
-        $sqlstring .= '))'
-    }
-    if ($branchesstring ne ''){
-        $sqlstring .= 'and biblio.biblionumber=items.biblionumber and (items.holdingbranch IN (';
-        my $branchesloop=0;
-        $extratables = ',items';
-        foreach my $branch (@branches){
-            if ($branch ne ''){
-                if ($branchesloop != 0){
-                    $sqlstring .=','
-                }
-                $sqlstring .= '"'.$branch.'"';
-                $branchesloop++;
-            }
+        elsif ( $i == $search_boxes_count ) {
+            push @search_boxes_array,
+              {
+                indexes      => $indexes,
+                left_content =>
+" <select name='op'><option value='and' selected='selected'>and</option><option value='or'>or</option><option value='not'>not</option></select>",
+                add_field => "1"
+              };
         }
-        $sqlstring .= '))'
-    }
-  if ($avail){
-       $extratables .= ',items,issues,reserves';
-    $sqlstring .= "and biblioitems.biblioitemnumber=items.biblioitemnumber and items.itemnumber !=issues.itemnumber and biblio.biblionumber !=reserves.biblionumber and (items.itemlost IS NULL or items.itemlost = 0) and (items.notforloan IS NULL or items.notforloan =0) and (items.wthdrawn IS NULL or items.wthdrawn =0) ";
-  }
-       my ($results,$total) = catalogsearch($dbh, \@tags,\@and_or,
-                                                                               \@excluding, \@operator, \@value,
-                                                                               $startfrom*$resultsperpage, $resultsperpage,$orderby,$desc_or_asc);
-       if ($total ==1) {
-       if (C4::Context->preference("BiblioDefaultView") eq "normal") {
-            print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=".@$results[0]->{biblionumber});
-       } elsif (C4::Context->preference("BiblioDefaultView") eq "marc") {
-            print $query->redirect("/cgi-bin/koha/opac-MARCdetail.pl?bib=".@$results[0]->{biblionumber});
-       } else {
-            print $query->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?bib=".@$results[0]->{biblionumber});
-       }
-       exit;
-       }
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-searchresults.tmpl",
-                               query => $query,
-                               type => 'opac',
-                               authnotrequired => 1,
-                               debug => 1,
-                               });
-
-       # multi page display gestion
-       my $displaynext=0;
-       my $displayprev=$startfrom;
-       if(($total - (($startfrom+1)*($resultsperpage))) > 0 ){
-               $displaynext = 1;
-       }
-
-       my @field_data = ();
-
-### Added by JF
-## This next does a number of things:
-# 1. It allows you to track all the searches made for stats, etc.
-# 2. It fixes the 'searchdesc' variable problem by introducing
-#         a. 'searchterms' which comes out as 'Keyword: neal stephenson'
-#         b. 'phraseorterm' which comes out as 'neal stephenson'
-#      both of these are useful for differen purposes ... I use searchterms
-#      for display purposes and phraseorterm for passing the search terms
-#      to an external source through a url (like a database search)
-# 3. It provides the variables necessary for the spellchecking (look below for
-#      how this is done
-# 4.
-$totalresults = $total;
-
-## This formats the 'search results' string and populates
-## the 'OPLIN' variable as well as the 'spellcheck' variable
-## with appropriate values based on the user's search input
-
-my $searchterms; #returned in place of searchdesc for 'results for search'
-                 # as a string (can format if need be)
-
-my @spphrases;
-my $phraseorterm;
-my %searchtypehash = ( # used only for the searchterms string formation
-                        # and for spellcheck string
-        '0' => 'keyword',
-        '1' => 'title',
-        '2' => 'author',
-        '3' => 'subject',
-        '4' => 'series',
-        '5' => 'format',
-        );
-
-my @searchterm = $query->param('value');
-
-for (my $i=0; $i <= $#searchterm; $i++) {
-        my $searchtype = $searchtypehash{$i};
-        push @spphrases, $searchterm[$i];
-        if ($searchterms) { #don't put and in again
-                if ($searchterm[$i]) {
-                $phraseorterm.=$searchterm[$i];
-                $searchterms.=" AND ".$searchtype." : \'".$searchterm[$i]."\'";
-                }
-        } else {
-                if ($searchterm[$i]) {
-                $phraseorterm.=$searchterm[$i];
-                $searchterms.=$searchtype.": \'".$searchterm[$i]."\'";
-                }
+        else {
+            push @search_boxes_array,
+              {
+                indexes      => $indexes,
+                left_content =>
+" <select name='op'><option value='and' selected='selected'>and</option><option value='or'>or</option><option value='not'>not</option></select>",
+              };
         }
+    }
+    $template->param(
+        uc( C4::Context->preference("marcflavour") ) => 1,
+        search_boxes_loop                            => \@search_boxes_array
+    );
+
+    # load the language limits (for search)
+    my $languages_limit_loop = getAllLanguages();
+    $template->param( search_languages_loop => $languages_limit_loop, );
+
+    # load the subtype limits
+    my $outer_subtype_limits_loop = displaySubtypesLimit();
+    $template->param( outer_subtype_limits_loop => $outer_subtype_limits_loop,
+    );
+
+    my $expanded_options;
+    if ( C4::Context->preference("expandedSearchOption") ) {
+        $expanded_options = C4::Context->preference("expandedSearchOption");
+    }
+    else {
+        $expanded_options = $cgi->param('expanded_options');
+    }
+
+    $template->param( expanded_options => $expanded_options );
+
+    # load the sort_by options for the template
+    my $sort_by      = $cgi->param('sort_by');
+    my $sort_by_loop = displaySortby($sort_by);
+    $template->param(
+        sort_by_loop => $sort_by_loop,
+        OpacCloud            => C4::Context->preference("OpacCloud"),
+        OpacTopissue         => C4::Context->preference("OpacTopissue"),
+        OpacAuthorities      => C4::Context->preference("OpacAuthorities"),
+     );
+
+    output_html_with_http_headers $cgi, $cookie, $template->output;
+    exit;
 }
 
-# Spellchecck stuff ... needs to use above scheme but must change
-# cgi script first
-my $phrases = $query->param('value');
-#my $searchterms = $query->param('value');
-# warn "here is searchterms:".$searchterms;
-
-# FIXME: should be obvious ;-)
-#foreach my $phrases (@spphrases) {
-$phrases =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
-$phrases =~ s/(\Athe |\Aa |\Aan |)//g;
-my $spchkphraseorterm = $phraseorterm;
-        $spchkphraseorterm =~ tr/A-Z/a-z/;
-        $spchkphraseorterm =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
-        $spchkphraseorterm =~s/(\Aand-or |\Aand\/or |\Aanon |\Aan |\Aa |\Abut |\Aby |\Ade |\Ader |\Adr |\Adu|et |\Afor |\Afrom |\Ain |\Ainto |\Ait |\Amy |\Anot |\Aon |\Aor |\Aper |\Apt |\Aspp |\Ato |\Avs |\Awith |\Athe )/ /g;
-        $spchkphraseorterm =~s/( and-or | and\/or | anon | an | a | but | by | de | der | dr | du|et | for | from | in | into | it | my | not | on | or | per | pt | spp | to | vs | with | the )/ /g;
-        $spchkphraseorterm =~s/  / /g;
-my $resultcount = $total;
-my $ipaddress = $query->remote_host();
+### OK, if we're this far, we're performing an actual search
+
+# Fetch the paramater list as a hash in scalar context:
+#  * returns paramater list as tied hash ref
+#  * we can edit the values by changing the key
+#  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
+my $params = $cgi->Vars;
+
+# Params that can have more than one value
+# sort by is used to sort the query
+my @sort_by;
+@sort_by = split( "\0", $params->{'sort_by'} ) if $params->{'sort_by'};
+
+# load the sort_by options for the template
+my $sort_by      = $params->{'sort_by'};
+my $sort_by_loop = displaySortby($sort_by);
+$template->param( sort_by_loop => $sort_by_loop );
+
 #
+# Use the servers defined, or just search our local catalog(default)
+my @servers;
+@servers = split( "\0", $params->{'server'} ) if $params->{'server'};
+unless (@servers) {
 
-if (
-#need to create a table to record the search info
-#...FIXME: add the script name that creates the table
-# 
-my $dbhpop=DBI->connect("DBI:mysql:demosuggest:localhost","auth","YourPass")) {
-
-# insert the search info query
-my $insertpop = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
-
-# grab spelling suggestions query
-my $getsugg = "SELECT display FROM spellcheck WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
-
-#get spelling suggestions when there are no results
-if ($resultcount eq 0) {
-        my $sthgetsugg=$dbhpop->prepare($getsugg);
-        $sthgetsugg->execute($spchkphraseorterm);
-        while (my ($spsuggestion)=$sthgetsugg->fetchrow_array) {
-#               warn "==>$spsuggestion";
-                #push @spsuggest, +{ spsuggestion => $spsuggestion };
-                my %line;
-                $line{spsuggestion} = $spsuggestion;
-                push @spsuggest,\%line;
-                $suggest = 1;
-        }
-#       warn "==>".$#spsuggest;
-        $sthgetsugg->finish;
+    #FIXME: this should be handled using Context.pm
+    @servers = ("biblioserver");
+
+    # @servers = C4::Context->config("biblioserver");
 }
-# end of spelling suggestions
 
-my $sthpop=$dbhpop->prepare($insertpop);
+# operators include boolean and proximity operators and are used
+# to evaluate multiple operands
+my @operators;
+@operators = split( "\0", $params->{'op'} ) if $params->{'op'};
+
+# indexes are query qualifiers, like 'title', 'author', etc. They
+# can be simple or complex
+my @indexes;
+@indexes = split( "\0", $params->{'idx'} ) if $params->{'idx'};
+
+# an operand can be a single term, a phrase, or a complete ccl query
+my @operands;
+@operands = split( "\0", $params->{'q'} ) if $params->{'q'};
+
+# limits are use to limit to results to a pre-defined category such as branch or language
+my @limits;
+@limits = split( "\0", $params->{'limit'} ) if $params->{'limit'};
 
-#$sthpop->execute($phrases,$resultcount,$ipaddress);
-$sthpop->finish;
+my $available;
+foreach my $limit (@limits) {
+    if ( $limit =~ /available/ ) {
+        $available = 1;
+    }
 }
-#
-### end of tracking stuff  --  jmf at kados dot org
-#
-$template->param(suggest => $suggest );
-$template->param( SPELL_SUGGEST => \@spsuggest );
-$template->param( searchterms => $searchterms );
-$template->param( phraseorterm => $phraseorterm );
-#warn "here's the search terms: ".$searchterms;
-#
-### end of spelling suggestions
-### /Added by JF
-
-       for(my $i = 0 ; $i <= $#marclist ; $i++)
-       {
-               push @field_data, { term => "marclist", val=>$marclist[$i] };
-               push @field_data, { term => "and_or", val=>$and_or[$i] };
-               push @field_data, { term => "excluding", val=>$excluding[$i] };
-               push @field_data, { term => "operator", val=>$operator[$i] };
-               push @field_data, { term => "value", val=>$value[$i] };
-       }
-       push @field_data, {term => "desc_or_asc", val => $desc_or_asc} if $desc_or_asc;
-       push @field_data, {term => "orderby", val => $orderby} if $orderby;
-       my @numbers = ();
-
-       if ($total>$resultsperpage)
-       {
-               for (my $i=1; $i<$total/$resultsperpage+1; $i++)
-               {
-                       if ($i<16)
-                       {
-                       my $highlight=0;
-                       ($startfrom==($i-1)) && ($highlight=1);
-                       push @numbers, { number => $i,
-                                       highlight => $highlight ,
-                                       searchdata=> \@field_data,
-                                       startfrom => ($i-1)};
-                       }
-       }
-       }
-
-       my $from = $startfrom*$resultsperpage+1;
-       my $to;
-
-       if($total < (($startfrom+1)*$resultsperpage))
-       {
-               $to = $total;
-       } else {
-               $to = (($startfrom+1)*$resultsperpage);
-       }
-       my $defaultview = 'BiblioDefaultView'.C4::Context->preference('BiblioDefaultView');
-       $template->param(results => $results,
-                                                       startfrom=> $startfrom,
-                                                       displaynext=> $displaynext,
-                                                       displayprev=> $displayprev,
-                                                       resultsperpage => $resultsperpage,
-                                                       orderby => $orderby,
-                                                       startfromnext => $startfrom+1,
-                                                       startfromprev => $startfrom-1,
-                                                       searchdata=>\@field_data,
-                                                       total=>$total,
-                                                       from=>$from,
-                                                       to=>$to,
-                                                       numbers=>\@numbers,
-                                                       searchdesc=> $searchdesc,
-                                                       $defaultview => 1,
-                                                       suggestion => C4::Context->preference("suggestion"),
-                                                       virtualshelves => C4::Context->preference("virtualshelves"),
-                                                       );
-
-} else {
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "opac-search.tmpl",
-                                       query => $query,
-                                       type => "opac",
-                                       authnotrequired => 1,
-                               });
-       
-       
-       my $query="Select itemtype,description from itemtypes order by description";
-       my $sth=$dbh->prepare($query);
-       $sth->execute;
-       my  @itemtypeloop;
-       my %itemtypes;
-       while (my ($value,$lib) = $sth->fetchrow_array) {
-               my %row =(      value => $value,
-                                       description => $lib,
-                               );
-               push @itemtypeloop, \%row;
-       }
-       $sth->finish;
-
-       my @oldbranches;
-       my @oldselect_branch;
-       my %oldselect_branches;
-       my ($oldcount2,@oldbranches)=branches();
-       push @oldselect_branch, "";
-       $oldselect_branches{''} = "";
-       for (my $i=0;$i<$oldcount2;$i++){
-               push @oldselect_branch, $oldbranches[$i]->{'branchcode'};#
-               $oldselect_branches{$oldbranches[$i]->{'branchcode'}} = $oldbranches[$i]->{'branchname'};
-       }
-       my $CGIbranch=CGI::scrolling_list( -name     => 'value',
-                               -values   => \@oldselect_branch,
-                               -labels   => \%oldselect_branches,
-                               -size     => 1,
-                               -multiple => 0 );
-       $sth->finish;
-       my @select_branch;
-       my %select_branches;
-       my $branches=GetBranches();
-       push @select_branch, "";
-       $select_branches{''} = "";
-        foreach my $branch ( keys %$branches ){
-               push @select_branch, $branches->{$branch}->{'branchcode'};
-               $select_branches{$branches->{$branch}->{'branchcode'}} = $branches->{$branch}->{'branchname'};
-       }
-       my $CGIbranch=CGI::scrolling_list( -name     => 'value',
-                               -values   => \@select_branch,
-                               -labels   => \%select_branches,
-                               -size     => 1,
-                               -multiple => 0 );
-       $sth->finish;
-    
-       $template->param('Disable_Dictionary'=>C4::Context->preference("Disable_Dictionary")) if (C4::Context->preference("Disable_Dictionary"));
-       $template->param(
-           
-# CHRIS : Whats this?      
-#          classlist => $classlist,
-                                       CGIbranch => $CGIbranch,
-                                       suggestion => C4::Context->preference("suggestion"),
-                                       virtualshelves => C4::Context->preference("virtualshelves"),
-                                       LibraryName => C4::Context->preference("LibraryName"),
-                                       OpacNav => C4::Context->preference("OpacNav"),
-                                       opaccredits => C4::Context->preference("opaccredits"),
-                                       AmazonContent => C4::Context->preference("AmazonContent"),
-                               opacsmallimage => C4::Context->preference("opacsmallimage"),
-                               opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
-                               opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
-       );
+$template->param( available => $available );
+push @limits, map "yr:" . $_, split( "\0", $params->{'limit-yr'} )
+  if $params->{'limit-yr'};
+
+# Params that can only have one value
+my $query            = $params->{'q'};
+my $scan             = $params->{'scan'};
+my $results_per_page = $params->{'count'} || 20;
+my $offset           = $params->{'offset'} || 0;
+my $hits;
+my $expanded_facet = $params->{'expand'};
+
+# Define some global variables
+my $error;          # used for error handling
+my $search_desc;    # the query expressed in terms that humans understand
+my $koha_query
+  ; # the query expressed in terms that zoom understands with field weighting and stemming
+my $federated_query;
+my $query_type
+  ; # usually not needed, but can be used to trigger ccl, cql, or pqf queries if set
+my @results;
+## I. BUILD THE QUERY
+( $error, $search_desc, $koha_query, $federated_query, $query_type ) =
+  buildQuery( $query, \@operators, \@operands, \@indexes, \@limits );
+
+# warn "query : $koha_query";
+## II. DO THE SEARCH AND GET THE RESULTS
+my $total;    # the total results for the whole set
+my $facets
+  ; # this object stores the faceted results that display on the left-hand of the results page
+my @results_array;
+my $results_hashref;
+
+eval {
+
+    ( $error, $results_hashref, $facets ) = getRecords(
+        $koha_query,     $federated_query,  \@sort_by,
+        \@servers,       $results_per_page, $offset,
+        $expanded_facet, $branches,         $query_type,
+        $scan
+    );
+
+};
+if ( $@ || $error ) {
+    $template->param( query_error => $error . $@ );
+
+    #     warn "error: ".$error.$@;
+    output_html_with_http_headers $cgi, $cookie, $template->output;
+    exit;
 }
-# ADDED BY JF
-if ($totalresults == 1){
-    # if its a barcode search by definition we will only have one result.
-    # And if we have a result
-    # lets jump straight to the detail.pl page
-    print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=$firstbiblionumber");
+
+# At this point, each server has given us a result set
+# now we build that set for template display
+my @sup_results_array;
+for ( my $i = 0 ; $i <= @servers ; $i++ ) {
+    my $server = $servers[$i];
+    if ( $server =~ /biblioserver/ ) {  # this is the local bibliographic server
+        $hits = $results_hashref->{$server}->{"hits"};
+        my @newresults =
+          searchResults( $search_desc, $hits, $results_per_page, $offset,
+            @{ $results_hashref->{$server}->{"RECORDS"} } );
+        $total = $total + $results_hashref->{$server}->{"hits"};
+        if ($hits) {
+            $template->param( total            => $hits );
+            $template->param( searchdesc       => $search_desc );
+            $template->param( results_per_page => $results_per_page );
+            $template->param( SEARCH_RESULTS   => \@newresults );
+
+            my @page_numbers;
+            my $pages               = ceil( $hits / $results_per_page );
+            my $current_page_number = 1;
+            $current_page_number = ( $offset / $results_per_page + 1 )
+              if $offset;
+            my $previous_page_offset = $offset - $results_per_page
+              unless ( $offset - $results_per_page < 0 );
+            my $next_page_offset = $offset + $results_per_page;
+            for ( $i = 1 ; $i <= $pages ; $i++ ) {
+                my $this_offset =
+                  ( ( $i * $results_per_page ) - $results_per_page );
+                my $this_page_number = $i;
+                my $highlight        = 1
+                  if ( $this_page_number == $current_page_number );
+                push @page_numbers,
+                  {
+                    offset    => $this_offset,
+                    pg        => $this_page_number,
+                    highlight => $highlight,
+                    sort_by   => join " ",
+                    @sort_by
+                  };
+            }
+            $template->param(
+                PAGE_NUMBERS         => \@page_numbers,
+                previous_page_offset => $previous_page_offset,
+                next_page_offset     => $next_page_offset
+            ) unless $pages < 2;
+        }
+    }    # end of the if local
+    else {
+
+        # check if it's a z3950 or opensearch source
+        my $zed3950 = 0;    # FIXME :: Hardcoded value.
+        if ($zed3950) {
+            my @inner_sup_results_array;
+            for my $sup_record ( @{ $results_hashref->{$server}->{"RECORDS"} } )
+            {
+                my $marc_record_object =
+                  MARC::Record->new_from_usmarc($sup_record);
+                my $control_number =
+                  $marc_record_object->field('010')->subfield('a')
+                  if $marc_record_object->field('010');
+                $control_number =~ s/^ //g;
+                my $link =
+                    "http://catalog.loc.gov/cgi-bin/Pwebrecon.cgi?SAB1="
+                  . $control_number
+                  . "&BOOL1=all+of+these&FLD1=LC+Control+Number+LCCN+%28K010%29+%28K010%29&GRP1=AND+with+next+set&SAB2=&BOOL2=all+of+these&FLD2=Keyword+Anywhere+%28GKEY%29+%28GKEY%29&PID=6211&SEQ=20060816121838&CNT=25&HIST=1";
+                my $title = $marc_record_object->title();
+                push @inner_sup_results_array,
+                  {
+                    'title' => $title,
+                    'link'  => $link,
+                  };
+            }
+            my $servername = $server;
+            push @sup_results_array,
+              {
+                servername             => $servername,
+                inner_sup_results_loop => \@inner_sup_results_array
+              };
+            $template->param( outer_sup_results_loop => \@sup_results_array );
+        }
+    }
+
+}    #/end of the for loop
+
+#$template->param(FEDERATED_RESULTS => \@results_array);
+# adding the $RequestOnOpac param
+my $RequestOnOpac;
+if (C4::Context->preference("RequestOnOpac")) {
+       $RequestOnOpac = 1;
 }
-else {
-  output_html_with_http_headers $query, $cookie, $template->output;
+
+$template->param(
+
+    #classlist => $classlist,
+    total                => $total,
+    searchdesc           => $search_desc,
+    opacfacets           => 1,
+    facets_loop          => $facets,
+    "BiblioDefaultView"
+      . C4::Context->preference("BiblioDefaultView") => 1,
+    scan_use     => $scan,
+    search_error => $error,
+    RequestOnOpac       => $RequestOnOpac,
+);
+## Now let's find out if we have any supplemental data to show the user
+#  and in the meantime, save the current query for statistical purposes, etc.
+my $koha_spsuggest;   # a flag to tell if we've got suggestions coming from Koha
+my @koha_spsuggest
+  ;    # place we store the suggestions to be returned to the template as LOOP
+my $phrases = $search_desc;
+my $ipaddress;
+
+if ( C4::Context->preference("kohaspsuggest") ) {
+    eval {
+        my $koha_spsuggest_dbh;
+
+        # FIXME: this needs to be moved to Context.pm
+        eval {
+            $koha_spsuggest_dbh =
+              DBI->connect( "DBI:mysql:suggest:66.213.78.76",
+                "auth", "Free2cirC" );
+        };
+        if ($@) {
+            warn "can't connect to spsuggest db";
+        }
+        else {
+            my $koha_spsuggest_insert =
+"INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
+            my $koha_spsuggest_query =
+"SELECT display FROM distincts WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
+            my $koha_spsuggest_sth =
+              $koha_spsuggest_dbh->prepare($koha_spsuggest_query);
+            $koha_spsuggest_sth->execute($phrases);
+            while ( my $spsuggestion = $koha_spsuggest_sth->fetchrow_array ) {
+                $spsuggestion =~ s/(:|\/)//g;
+                my %line;
+                $line{spsuggestion} = $spsuggestion;
+                push @koha_spsuggest, \%line;
+                $koha_spsuggest = 1;
+            }
+
+            # Now save the current query
+            $koha_spsuggest_sth =
+              $koha_spsuggest_dbh->prepare($koha_spsuggest_insert);
+
+           #$koha_spsuggest_sth->execute($phrases,$results_per_page,$ipaddress);
+            $koha_spsuggest_sth->finish;
+            $template->param( koha_spsuggest => $koha_spsuggest ) unless $hits;
+            $template->param( SPELL_SUGGEST => \@koha_spsuggest, );
+        }
+    };
+    if ($@) {
+        warn "Kohaspsuggest failure:" . $@;
+    }
 }
+
+# VI. BUILD THE TEMPLATE
+output_html_with_http_headers $cgi, $cookie, $template->output;
index 9fc6553..87e71b6 100755 (executable)
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 require Exporter;
 use CGI;
 use Mail::Sendmail;
 use MIME::QuotedPrint;
 use MIME::Base64;
-
-use C4::Search;
 use C4::Biblio;
 use C4::Auth;
 use C4::Interface::CGI::Output;
 use C4::Biblio;
-use HTML::Template;
 
 my $query = new CGI;
 
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-sendbasketform.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                        });
-
-my $bib_list=$query->param('bib_list');
-my $email_add=$query->param('email_add');
-my $email_sender=$query->param('email_sender');
-my $dbh=C4::Context->dbh;
-my $sth;
-$sth=$dbh->prepare("select bibid from marc_biblio where biblionumber=? order by bibid");
-
-
-if ($email_add) {
-       my $email_from = C4::Context->preference('KohaAdminEmailAddress');
-
-       my %mail = (     To      => $email_add,
-                                                From    => $email_from);
-
-       my ($template2, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-sendbasket.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                        });
-
-       my @bibs = split(/\//, $bib_list);
-       my @results;
-       my $iso2709;
-       foreach my $biblionumber (@bibs) {
-               $template2->param(biblionumber => $biblionumber);
-
-               my $dat = &bibdata($biblionumber);
-               my ($authorcount, $addauthor) = &addauthor($biblionumber);
-               my @items                     = &ItemInfo(undef, $biblionumber, 'opac');
-
-               $dat->{'additional'}=$addauthor->[0]->{'author'};
-               for (my $i = 1; $i < $authorcount; $i++) {
-                       $dat->{'additional'} .= "|" . $addauthor->[$i]->{'author'};
-               }
-
-               $dat->{'biblionumber'} = $biblionumber;
-               $dat->{ITEM_RESULTS} = \@items;
-               $sth->execute($biblionumber);
-               my ($bibid) = $sth->fetchrow;
-               my $record = MARCgetbiblio($dbh,$bibid);
-               $iso2709 .= $record->as_usmarc();
-
-               push (@results, $dat);
-       }
-
-       my $resultsarray=\@results;
-       $template2->param(BIBLIO_RESULTS => $resultsarray,
-                                       email_sender => $email_sender);
-
-       # Getting template result
-       my $template_res = $template2->output();
-       my $body;
-
-       # Analysing information and getting mail properties
-       if ($template_res =~ /<SUBJECT>\n(.*)\n<END_SUBJECT>/s) { $mail{'subject'} = $1; }
-       else { $mail{'subject'} = "no subject"; }
-
-       my $email_header = "";
-       if ($template_res =~ /<HEADER>\n(.*)\n<END_HEADER>/s) { $email_header = $1; }
-
-       my $email_file = "basket.txt";
-       if ($template_res =~ /<FILENAME>\n(.*)\n<END_FILENAME>/s) { $email_file = $1; }
-
-       if ($template_res =~ /<MESSAGE>\n(.*)\n<END_MESSAGE>/s) { $body = $1; }
-
-       my $boundary = "====" . time() . "====";
-#      $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
-# 
-#      $email_header = encode_qp($email_header);
-# 
-#      $boundary = "--".$boundary;
-# 
-#      # Writing mail
-#      $mail{body} =
-       $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
-       my $isofile = encode_base64($iso2709);
-       $boundary = '--'.$boundary;
-       $mail{body} = 
-<<END_OF_BODY;
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user (
+    {
+        template_name   => "opac-sendbasketform.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+        flagsrequired   => { borrow => 1 },
+    }
+);
+
+my $bib_list     = $query->param('bib_list');
+my $email_add    = $query->param('email_add');
+my $email_sender = $query->param('email_sender');
+
+my $dbh          = C4::Context->dbh;
+
+if ( $email_add ) {
+    my $email_from = C4::Context->preference('KohaAdminEmailAddress');
+    my $comment    = $query->param('comment');
+    my %mail = (
+        To   => $email_add,
+        From => $email_from
+    );
+
+    my ( $template2, $borrowernumber, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-sendbasket.tmpl",
+            query           => $query,
+            type            => "opac",
+            authnotrequired => 1,
+            flagsrequired   => { borrow => 1 },
+        }
+    );
+
+    my @bibs = split( /\//, $bib_list );
+    my @results;
+    my $iso2709;
+    my $marcflavour = C4::Context->preference('marcflavour');
+    foreach my $biblionumber (@bibs) {
+        $template2->param( biblionumber => $biblionumber );
+
+        my $dat              = GetBiblioData($biblionumber);
+        my $record           = GetMarcBiblio($biblionumber);
+        my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
+        my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
+        my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
+
+        my @items = &GetItemsInfo( $biblionumber, 'opac' );
+
+        $dat->{MARCNOTES}      = $marcnotesarray;
+        $dat->{MARCSUBJCTS}    = $marcsubjctsarray;
+        $dat->{MARCAUTHORS}    = $marcauthorsarray;
+        $dat->{'biblionumber'} = $biblionumber;
+        $dat->{ITEM_RESULTS}   = \@items;
+
+        $iso2709 .= $record->as_usmarc();
+
+        push( @results, $dat );
+    }
+
+    my $resultsarray = \@results;
+    $template2->param(
+        BIBLIO_RESULTS => $resultsarray,
+        email_sender   => $email_sender,
+        comment        => $comment
+    );
+
+    # Getting template result
+    my $template_res = $template2->output();
+    my $body;
+
+    # Analysing information and getting mail properties
+    if ( $template_res =~ /<SUBJECT>\n(.*)\n<END_SUBJECT>/s ) {
+        $mail{'subject'} = $1;
+    }
+    else { $mail{'subject'} = "no subject"; }
+
+    my $email_header = "";
+    if ( $template_res =~ /<HEADER>\n(.*)\n<END_HEADER>/s ) {
+        $email_header = $1;
+    }
+
+    my $email_file = "basket.txt";
+    if ( $template_res =~ /<FILENAME>\n(.*)\n<END_FILENAME>/s ) {
+        $email_file = $1;
+    }
+
+    if ( $template_res =~ /<MESSAGE>\n(.*)\n<END_MESSAGE>/s ) { $body = $1; }
+
+    my $boundary = "====" . time() . "====";
+
+    #     $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
+    #
+    #     $email_header = encode_qp($email_header);
+    #
+    #     $boundary = "--".$boundary;
+    #
+    #     # Writing mail
+    #     $mail{body} =
+    $mail{'content-type'} = "multipart/mixed; boundary=\"$boundary\"";
+    my $isofile = encode_base64($iso2709);
+    $boundary = '--' . $boundary;
+    $mail{body} = <<END_OF_BODY;
 $boundary
 Content-Type: text/plain; charset="iso-8859-1"
 Content-Transfer-Encoding: quoted-printable
@@ -118,22 +145,25 @@ $isofile
 $boundary--
 END_OF_BODY
 
-       # Sending mail
-       if (sendmail %mail) {
-       # do something if it works....
-               $template->param(SENT => "1");
-               $template->param(email_add => $email_add);
-       } else {
-               # do something if it doesnt work....
-               warn "Error sending mail: $Mail::Sendmail::error \n";
-       }
-       output_html_with_http_headers $query, $cookie, $template->output;
+    # Sending mail
+    if ( sendmail %mail ) {
+        # do something if it works....
+        $template->param( SENT      => "1" );
+    }
+    else {
+        # do something if it doesnt work....
+        warn "Error sending mail: $Mail::Sendmail::error \n";
+        $template->param( error => 1 );
+    }
+    $template->param( email_add => $email_add );
+    output_html_with_http_headers $query, $cookie, $template->output;
 }
 else {
-       $template->param(bib_list => $bib_list);
-       $template->param(url => "/cgi-bin/koha/opac-sendbasket.pl",
-       suggestion => C4::Context->preference("suggestion"),
-       virtualshelves => C4::Context->preference("virtualshelves"),
-       );
-       output_html_with_http_headers $query, $cookie, $template->output;
+    $template->param( bib_list => $bib_list );
+    $template->param(
+        url            => "/cgi-bin/koha/opac-sendbasket.pl",
+        suggestion     => C4::Context->preference("suggestion"),
+        virtualshelves => C4::Context->preference("virtualshelves"),
+    );
+    output_html_with_http_headers $query, $cookie, $template->output;
 }
index 05afe0e..493b70d 100755 (executable)
@@ -29,63 +29,69 @@ use C4::Letters;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use HTML::Template;
 
-my $query = new CGI;
-my $op = $query->param('op');
-my $dbh = C4::Context->dbh;
+
+my $query      = new CGI;
+my $op         = $query->param('op');
+my $dbh        = C4::Context->dbh;
 my $selectview = $query->param('selectview');
 $selectview = C4::Context->preference("SubscriptionHistory") unless $selectview;
 
 my $sth;
+
 # my $id;
-my ($template, $loggedinuser, $cookie);
+my ( $template, $loggedinuser, $cookie );
 my $biblionumber = $query->param('biblionumber');
-if ($selectview eq "full"){
-       my $subscriptions = GetFullSubscriptionsFromBiblionumber($biblionumber);
-       
-       my $title = $subscriptions->[0]{bibliotitle};
-       my $yearmin=$subscriptions->[0]{year};
-       my $yearmax=$subscriptions->[scalar(@$subscriptions)-1]{year};
+if ( $selectview eq "full" ) {
+    my $subscriptions = GetFullSubscriptionsFromBiblionumber($biblionumber);
+
+    my $title   = $subscriptions->[0]{bibliotitle};
+    my $yearmin = $subscriptions->[0]{year};
+    my $yearmax = $subscriptions->[ scalar(@$subscriptions) - 1 ]{year};
+
+    ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-full-serial-issues.tmpl",
+            query           => $query,
+            type            => "opac",
+            authnotrequired => 1,
+            debug           => 1,
+        }
+    );
+
+    # replace CR by <br> in librarian note
+    # $subscription->{opacnote} =~ s/\n/\<br\/\>/g;
+
+    $template->param(
+        biblionumber   => $query->param('biblionumber'),
+        years          => $subscriptions,
+        yearmin        => $yearmin,
+        yearmax        => $yearmax,
+        bibliotitle    => $title,
+        suggestion     => C4::Context->preference("suggestion"),
+        virtualshelves => C4::Context->preference("virtualshelves"),
+    );
+
+}
+else {
+    my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber);
+
+    ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-serial-issues.tmpl",
+            query           => $query,
+            type            => "opac",
+            authnotrequired => 1,
+            debug           => 1,
+        }
+    );
 
-       ($template, $loggedinuser, $cookie)
-       = get_template_and_user({template_name => "opac-full-serial-issues.tmpl",
-                                       query => $query,
-                                       type => "opac",
-                                       authnotrequired => 1,
-                                       debug => 1,
-                                       });
-       
-       # replace CR by <br> in librarian note
-       # $subscription->{opacnote} =~ s/\n/\<br\/\>/g;
-       
-       $template->param(
-               biblionumber => $query->param('biblionumber'),
-               years => $subscriptions,
-               yearmin => $yearmin,
-               yearmax =>$yearmax,
-               bibliotitle => $title,
-               suggestion => C4::Context->preference("suggestion"),
-               virtualshelves => C4::Context->preference("virtualshelves"),
-               );
+    # replace CR by <br> in librarian note
+    # $subscription->{opacnote} =~ s/\n/\<br\/\>/g;
 
-} else {
-       my $subscriptions = GetSubscriptionsFromBiblionumber($biblionumber);
-       
-       ($template, $loggedinuser, $cookie)
-       = get_template_and_user({template_name => "opac-serial-issues.tmpl",
-                                       query => $query,
-                                       type => "opac",
-                                       authnotrequired => 1,
-                                       debug => 1,
-                                       });
-       
-       # replace CR by <br> in librarian note
-       # $subscription->{opacnote} =~ s/\n/\<br\/\>/g;
-       
-       $template->param(
-               biblionumber => $query->param('biblionumber'),
-               subscription_LOOP => $subscriptions,
-               );
+    $template->param(
+        biblionumber      => $query->param('biblionumber'),
+        subscription_LOOP => $subscriptions,
+    );
 }
 output_html_with_http_headers $query, $cookie, $template->output;
index 5e252e0..e58fe28 100755 (executable)
@@ -1,9 +1,5 @@
 #!/usr/bin/perl
-#script to provide bookshelf management
-# WARNING: This file uses 4-character tabs!
-#
-# $Header$
-#
+
 # Copyright 2000-2002 Katipo Communications
 #
 # This file is part of Koha.
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
+# $Id$
+
+=head1 NAME
+
+    opac-shelves.pl
+
+=head1 DESCRIPTION
+
+    this script is used to script to provide bookshelf management
+
+=head1 CGI PARAMETERS
+
+=over 4
+
+=item C<modifyshelfcontents>
+
+    if this script has to modify the shelve content.
+
+=item C<shelfnumber>
+
+    to know on which shelve this script has to work.
+
+=item C<addbarcode>
+
+=item C<op>
+
+    op can be equals to:
+        * modifsave to save change on the shelves
+        * modif to change the template to allow to modify the shelves.
+
+=item C<viewshelf>
+
+    to load the template with 'viewshelves param' which allow to read the shelves information.
+
+=item C<shelves>
+
+    if equals to 1. then call the function shelves which add
+    or delete a shelf.
+
+=item C<addshelf>
+
+    if the param shelves = 1 then addshelf must be equals to the name of the shelf to add.
+
+=back
+
+=cut
+
 use strict;
-use C4::Search;
 use CGI;
 use C4::Output;
 use C4::BookShelves;
 use C4::Circulation::Circ2;
 use C4::Auth;
 use C4::Interface::CGI::Output;
-use HTML::Template;
 
-my $env;
 my $query = new CGI;
 
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "opac-shelves.tmpl",
-                                                       query => $query,
-                                                       type => "opac",
-                                                       authnotrequired => 1,
-                                               });
-
-if ($query->param('modifyshelfcontents')) {
-       my $shelfnumber=$query->param('shelfnumber');
-       my $barcode=$query->param('addbarcode');
-       my ($item) = getiteminformation($env, 0, $barcode);
-       if (ShelfPossibleAction($loggedinuser,$shelfnumber,'manage')) {
-               AddToShelf($env, $item->{'itemnumber'}, $shelfnumber);
-               foreach ($query->param) {
-                       if (/REM-(\d*)/) {
-                               my $itemnumber=$1;
-                               RemoveFromShelf($env, $itemnumber, $shelfnumber);
-                       }
-               }
-       }
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-shelves.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+    }
+);
+
+if ( $query->param('modifyshelfcontents') ) {
+    my $shelfnumber = $query->param('viewshelf');
+    my $barcode     = $query->param('addbarcode');
+    my ($item) = getiteminformation( 0, $barcode );
+    if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' ) ) {
+        AddToShelf( $item->{'itemnumber'}, $shelfnumber );
+        foreach ( $query->param ) {
+            if (/MOD-(\d*)/) {
+                my $itemnumber = $1;
+                if ( $query->param('remove') eq "on" ) {
+                    DelFromShelf( $itemnumber, $shelfnumber );
+                }
+            }
+        }
+    }
 }
-my ($shelflist) = GetShelfList($loggedinuser,2);
 
-$template->param({     loggedinuser => $loggedinuser,
-                               });
+# getting the Shelves list
+my $shelflist = GetShelves( $loggedinuser, 2 );
+$template->param( { loggedinuser => $loggedinuser } );
+my $op = $query->param('op');
+
 SWITCH: {
-       if ($query->param('op') eq 'modifsave') {
-               ModifShelf($query->param('shelfnumber'),$query->param('shelfname'),$loggedinuser,$query->param('category'));
-               last SWITCH;
-       }
-       if ($query->param('op') eq 'modif') {
-               my ($shelfnumber,$shelfname,$owner,$category) = GetShelf($query->param('shelf'));
-               $template->param(edit => 1,
-                                               shelfnumber => $shelfnumber,
-                                               shelfname => $shelfname,
-                                               "category$category" => 1);
-#              editshelf($query->param('shelf'));
-               last SWITCH;
-       }
-       if ($query->param('viewshelf')) {
-               viewshelf($query->param('viewshelf'));
-               last SWITCH;
-       }
-       if ($query->param('shelves')) {
-               shelves();
-               last SWITCH;
-       }
+    if ( $op && ( $op eq 'modifsave' ) ) {
+        ModShelf(
+            $query->param('shelfnumber'), $query->param('shelfname'),
+            $loggedinuser,                $query->param('category')
+        );
+        last SWITCH;
+    }
+    if ( $op && ( $op eq 'modif' ) ) {
+        my ( $shelfnumber, $shelfname, $owner, $category ) =
+          GetShelf( $query->param('shelf') );
+        $template->param(
+            edit                => 1,
+            shelfnumber         => $shelfnumber,
+            shelfname           => $shelfname,
+            "category$category" => 1
+        );
+
+        #         editshelf($query->param('shelf'));
+        last SWITCH;
+    }
+    if ( $query->param('viewshelf') ) {
+        #check that the user can view the shelf
+        my $shelfnumber = $query->param('viewshelf');
+        if ( ShelfPossibleAction( $loggedinuser, $shelfnumber, 'view' ) ) {
+            my $items = GetShelfContents($shelfnumber);
+            $template->param(
+                shelfname   => $shelflist->{$shelfnumber}->{'shelfname'},
+                shelfnumber => $shelfnumber,
+                viewshelf   => $query->param('viewshelf'),
+                manageshelf => &ShelfPossibleAction( $loggedinuser, $shelfnumber, 'manage' ),
+                itemsloop   => $items,
+            );
+        }
+        last SWITCH;
+    }
+    if ( $query->param('shelves') ) {
+        if ( my $newshelf = $query->param('addshelf') ) {
+            my $shelfnumber = AddShelf(
+                $newshelf,
+                $query->param('owner'),
+                $query->param('category')
+            );
+
+            if ( $shelfnumber == -1 ) {    #shelf already exists.
+                $template->param(
+                    {
+                        shelfnumber => $shelfnumber,
+                        already     => 1
+                    }
+                );
+            }
+    }
+    my @paramsloop;
+    foreach ( $query->param() ) {
+        my %line;
+        if (/DEL-(\d+)/) {
+            my $delshelf = $1;
+            my ( $status, $count ) = DelShelf($delshelf);
+            if ($status) {
+                $line{'status'} = $status;
+                $line{'count'}  = $count;
+            }
+        }
+
+        #if the shelf is not deleted, %line points on null
+        push( @paramsloop, \%line );
+    }
+    $template->param( paramsloop => \@paramsloop );
+    my ($shelflist) = GetShelves( $loggedinuser, 2 );
+    my $color = '';
+    my @shelvesloop;
+    foreach my $element ( sort keys %$shelflist ) {
+        my %line;
+        ( $color eq 1 ) ? ( $color = 0 ) : ( $color = 1 );
+        $line{'toggle'}         = $color;
+        $line{'shelf'}          = $element;
+        $line{'shelfname'}      = $shelflist->{$element}->{'shelfname'};
+        $line{'shelfbookcount'} = $shelflist->{$element}->{'count'};
+        push( @shelvesloop, \%line );
+    }
+    $template->param(
+        shelvesloop => \@shelvesloop,
+        shelves     => 1,
+    );
+        last SWITCH;
+    }
 }
 
-($shelflist) = GetShelfList($loggedinuser,2); # rebuild shelflist in case a shelf has been added
+($shelflist) =
+  GetShelves( $loggedinuser, 2 )
+  ;    # rebuild shelflist in case a shelf has been added
 
-my $color='';
+my $color = '';
 my @shelvesloop;
-foreach my $element (sort keys %$shelflist) {
-               my %line;
-               ($color eq 0) ? ($color=1) : ($color=0);
-               $line{'color'}= $color;
-               $line{'shelf'}=$element;
-               $line{'shelfname'}=$shelflist->{$element}->{'shelfname'};
-               $line{"category".$shelflist->{$element}->{'category'}} = 1;
-               $line{'mine'} = 1 if $shelflist->{$element}->{'owner'} eq $loggedinuser;
-               $line{'shelfbookcount'}=$shelflist->{$element}->{'count'};
-               $line{'canmanage'} = ShelfPossibleAction($loggedinuser,$element,'manage');
-               $line{'firstname'}=$shelflist->{$element}->{'firstname'} unless $shelflist->{$element}->{'owner'} eq $loggedinuser;
-               $line{'surname'}=$shelflist->{$element}->{'surname'} unless $shelflist->{$element}->{'owner'} eq $loggedinuser;
-;
-               push (@shelvesloop, \%line);
-}
-$template->param(shelvesloop => \@shelvesloop);
+foreach my $element ( sort keys %$shelflist ) {
+    my %line;
+    ( $color eq 1 ) ? ( $color = 0 ) : ( $color = 1 );
+    $line{'toggle'}    = $color;
+        $line{'shelf'}     = $element;
+        $line{'shelfname'} = $shelflist->{$element}->{'shelfname'};
+        $line{ "category" . $shelflist->{$element}->{'category'} } = 1;
+        $line{'mine'} = 1 if $shelflist->{$element}->{'owner'} eq $loggedinuser;
+        $line{'shelfbookcount'} = $shelflist->{$element}->{'count'};
+        $line{'canmanage'}      =
+          ShelfPossibleAction( $loggedinuser, $element, 'manage' );
+        $line{'firstname'} = $shelflist->{$element}->{'firstname'}
+          unless $shelflist->{$element}->{'owner'} eq $loggedinuser;
+        $line{'surname'} = $shelflist->{$element}->{'surname'}
+          unless $shelflist->{$element}->{'owner'} eq $loggedinuser;
+        push( @shelvesloop, \%line );
+    }
+
+$template->param(
+    shelvesloop             => \@shelvesloop,
+    "BiblioDefaultView".C4::Context->preference("BiblioDefaultView") => 1,
+);
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
-# sub editshelf {
-#      my ($shelfnumber) = @_;
-#      my ($shelfnumber,$shelfname,$owner,$category) = GetShelf($shelfnumber);
-#      $template->param(edit => 1,
-#                                      shelfnumber => $shelfnumber,
-#                                      shelfname => $shelfname,
-#                                      "category$category" => 1);
-# }
-sub shelves {
-       if (my $newshelf=$query->param('addshelf')) {
-               my ($status, $string) = AddShelf($env,$newshelf,$query->param('owner'),$query->param('category'));
-               if ($status) {
-                       $template->param(status1 => $status, string1 => $string);
-               }
-       }
-       my @paramsloop;
-       foreach ($query->param()) {
-               my %line;
-               if (/DEL-(\d+)/) {
-                       my $delshelf=$1;
-                       my ($status, $string) = RemoveShelf($env,$delshelf);
-                       if ($status) {
-                               $line{'status'}=$status;
-                               $line{'string'} = $string;
-                       }
-               }
-               #if the shelf is not deleted, %line points on null
-               push(@paramsloop,\%line);
-       }
-       $template->param(paramsloop => \@paramsloop);
-       my ($shelflist) = GetShelfList($loggedinuser,2);
-       my $color='';
-       my @shelvesloop;
-       foreach my $element (sort keys %$shelflist) {
-               my %line;
-               ($color eq 0) ? ($color=1) : ($color=0);
-               $line{'color'}=$color;
-               $line{'shelf'}=$element;
-               $line{'shelfname'}=$shelflist->{$element}->{'shelfname'} ;
-               $line{'shelfbookcount'}=$shelflist->{$element}->{'count'} ;
-               push(@shelvesloop, \%line);
-       }
-       $template->param(shelvesloop=>\@shelvesloop,
-                                                       shelves => 1,
-                                               );
-}
 
-sub viewshelf {
-       my $shelfnumber=shift;
-       #check that the user can view the shelf
-       return unless (ShelfPossibleAction($loggedinuser,$shelfnumber,'view'));
-       my ($itemlist) = GetShelfContents($env, $shelfnumber);
-       my $item='';
-       my $color='';
-       my @itemsloop;
-       foreach $item (sort {$a->{'barcode'} cmp $b->{'barcode'}} @$itemlist) {
-               my %line;
-               ($color eq 0) ? ($color=1) : ($color=0);
-               $line{'color'}=$color;
-               $line{'itemnumber'}=$item->{'itemnumber'};
-               $line{'barcode'}=$item->{'barcode'};
-               $line{'title'}=$item->{'title'};
-               $line{'author'}=$item->{'author'};
-               $line{'classification'}=$item->{'classification'};              
-               $line{'itemtype'}=$item->{'itemtype'};          
-               $line{biblionumber} = $item->{biblionumber};
-               push(@itemsloop, \%line);
-       }
-       $template->param(       itemsloop => \@itemsloop,
-                                               shelfname => $shelflist->{$shelfnumber}->{'shelfname'},
-                                               shelfnumber => $shelfnumber,
-                                               viewshelf => $query->param('viewshelf'),
-                                               manageshelf => &ShelfPossibleAction($loggedinuser,$shelfnumber,'manage'),
-                                       );
-}
 
 #
 # $Log$
-# Revision 1.8  2006/05/21 02:30:17  kados
-# syncing dev-week and HEAD
-#
-# Revision 1.7  2005/05/04 09:02:38  tipaul
-# synch'ing 2.2 and head
-#
-# Revision 1.3.2.4  2005/03/25 17:04:28  tipaul
-# adding virtual shelves & suggestions button to the top
-#
-# Revision 1.3.2.3  2005/01/27 17:18:28  oleonard
-# Taking table cell background color information out of the script and moving it into the template (requires update to opac-shelves.tmpl)
-#
-# Revision 1.3.2.2  2005/01/11 20:18:29  oleonard
-# Adding call number and item type to list of returned variables
-#
-# Revision 1.3.2.1  2005/01/11 16:33:57  tipaul
-# fix for http://bugs.koha.org/cgi-bin/bugzilla/show_bug.cgi?id=811 :
-# The OPAC requires uses to log in to view virtual shelves, and it requires a user
-# with librarian privileges.  Virtual shelves should be viewable by all users,
-# logged in or not, and editable by all logged-in users in good standing.
-#
-# Revision 1.3  2005/01/03 11:09:34  tipaul
-# synch'ing virtual shelves management in opac with the librarian one, that has more features
-#
-# Revision 1.5  2004/12/16 11:30:57  tipaul
-# adding bookshelf features :
-# * create bookshelf on the fly
-# * modify a bookshelf name & status
-#
-# Revision 1.4  2004/12/15 17:28:23  tipaul
-# adding bookshelf features :
-# * create bookshelf on the fly
-# * modify a bookshelf (this being not finished, will commit the rest soon)
+# Revision 1.9  2007/03/09 15:12:54  tipaul
+# rel_3_0 moved to HEAD
 #
-# Revision 1.3  2004/12/02 16:38:50  tipaul
-# improvement in book shelves
+# Revision 1.8.2.12  2007/01/15 17:19:30  toins
+# enable to add checked items to a shelf.
+# Some display enhancements.
 #
-# Revision 1.2  2004/11/19 16:31:30  tipaul
-# bugfix for bookshelves not in official CVS
+# Revision 1.8.2.11  2007/01/10 10:52:58  toins
+# adding syspref directly to Auth.pm instead of to the template.
 #
-# Revision 1.1.2.1  2004/03/10 15:08:18  tipaul
-# modifying shelves : introducing category of shelf : private, public, free for all
+# Revision 1.8.2.10  2007/01/10 10:12:48  toins
+# Adding OpacTopissue, OpacCloud, OpacAuthorithies to the template->param.
+# + Some cleanup.
 #
-# Revision 1.13  2004/02/11 08:35:31  tipaul
-# synch'ing 2.0.0 branch and head
+# Revision 1.8.2.9  2006/12/15 17:43:24  toins
+# sync with intranet.
 #
-# Revision 1.12.2.1  2004/02/06 14:22:19  tipaul
-# fixing bugs in bookshelves management.
+# Revision 1.8.2.8  2006/12/14 17:59:17  toins
+# add the link to "BiblioDefaultView systempref" and not to opac-detail.pl
 #
-# Revision 1.12  2003/02/05 10:04:14  acli
-# Worked around weirdness with HTML::Template; without the {}, it complains
-# of being passed an odd number of arguments even though we are not
+# Revision 1.8.2.7  2006/12/14 17:22:55  toins
+# bookshelves work perfectly with mod_perl and are cleaned.
 #
-# Revision 1.11  2003/02/05 09:23:03  acli
-# Fixed a few minor errors to make it run
-# Noted correct tab size
+# Revision 1.8.2.6  2006/12/14 16:04:25  toins
+# sync with intranet.
 #
-# Revision 1.10  2003/02/02 07:18:37  acli
-# Moved C4/Charset.pm to C4/Interface/CGI/Output.pm
+# Revision 1.8.2.5  2006/12/11 17:10:06  toins
+# fixing some bugs on bookshelves.
 #
-# Create output_html_with_http_headers function to contain the "print $query
-# ->header(-type => guesstype...),..." call. This is in preparation for
-# non-HTML output (e.g., text/xml) and charset conversion before output in
-# the future.
+# Revision 1.8.2.4  2006/12/07 15:42:15  toins
+# synching opac & intranet.
+# fix some broken link & bugs.
+# removing warn compilation.
 #
-# Created C4/Interface/CGI/Template.pm to hold convenience functions specific
-# to the CGI interface using HTML::Template
+# Revision 1.8.2.3  2006/11/30 18:23:51  toins
+# theses scripts don't need to use C4::Search.
 #
-# Modified moremembers.pl to make the "sex" field localizable for languages
-# where M and F doesn't make sense
-#
-# Revision 1.9  2002/12/19 18:55:40  hdl
-# Templating reservereport et shelves.
-#
-# Revision 1.9  2002/08/14 18:12:51  hdl
-# Templating files
-#
-# Revision 1.8  2002/08/14 18:12:51  tonnesen
-# Added copyright statement to all .pl and .pm files
-#
-# Revision 1.7  2002/07/05 05:03:37  tonnesen
-# Minor changes to authentication routines.
-#
-# Revision 1.5  2002/07/04 19:42:48  tonnesen
-# Minor changes
-#
-# Revision 1.4  2002/07/04 19:21:29  tonnesen
-# Beginning of authentication api.  Applied to shelves.pl for now as a test case.
-#
-# Revision 1.2.2.1  2002/06/26 20:28:15  tonnesen
-# Some udpates that I made here locally a while ago.  Still won't be useful, but
-# should be functional
-#
-#
-#
-
-
-
-
-# Local Variables:
-# tab-width: 4
-# End:
index 2be12c8..8f52b9c 100755 (executable)
@@ -1,34 +1,52 @@
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 require Exporter;
 use CGI;
-
 use C4::Auth;
 use C4::Koha;
-use HTML::Template;
 use C4::Interface::CGI::Output;
-use C4::Search;
 use C4::Circulation::Circ2;
 use C4::Review;
 use C4::Biblio;
 
-my $query = new CGI;
+my $query        = new CGI;
 my $biblionumber = $query->param('biblionumber');
 
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-showreviews.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = &get_template_and_user(
+    {
+        template_name   => "opac-showreviews.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 1,
+    }
+);
 
-my $biblio=bibdata($biblionumber,'opac');
-my $reviews=getreviews($biblionumber,1);
+my $biblio  = GetBiblioData( $biblionumber,'opac' );
+my $reviews = getreviews( $biblionumber, 1 );
 
-$template->param('reviews' => $reviews,
-'title' => $biblio->{'title'});
+$template->param(
+    reviews => $reviews,
+    title   => $biblio->{'title'},
+    OpacCloud            => C4::Context->preference("OpacCloud"),
+    OpacTopissue         => C4::Context->preference("OpacTopissue"),
+    OpacAuthorities      => C4::Context->preference("OpacAuthorities"),
+);
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
index 02687aa..cdec0e7 100755 (executable)
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 require Exporter;
 use CGI;
-use HTML::Template;
-
-use C4::Auth;       # get_template_and_user
+use C4::Auth;    # get_template_and_user
 use C4::Interface::CGI::Output;
 use C4::Suggestions;
 
-my $input = new CGI;
-my $title = $input->param('title');
-my $author = $input->param('author');
-my $note = $input->param('note');
-my $copyrightdate =$input->param('copyrightdate');
-my $publishercode = $input->param('publishercode');
-my $volumedesc = $input->param('volumedesc');
+my $input           = new CGI;
+my $title           = $input->param('title');
+my $author          = $input->param('author');
+my $note            = $input->param('note');
+my $copyrightdate   = $input->param('copyrightdate');
+my $publishercode   = $input->param('publishercode');
+my $volumedesc      = $input->param('volumedesc');
 my $publicationyear = $input->param('publicationyear');
-my $place = $input->param('place');
-my $isbn = $input->param('isbn');
-my $status = $input->param('status');
-my $suggestedbyme = $input->param('suggestedbyme');
-my $op = $input->param('op');
+my $place           = $input->param('place');
+my $isbn            = $input->param('isbn');
+my $status          = $input->param('status');
+my $suggestedbyme   = $input->param('suggestedbyme');
+my $op              = $input->param('op');
 $op = 'else' unless $op;
 
-my ($template, $borrowernumber, $cookie);
+my ( $template, $borrowernumber, $cookie );
 
 my $dbh = C4::Context->dbh;
 
-if (C4::Context->preference("AnonSuggestions")) {
-       ($template, $borrowernumber, $cookie)
-               = get_template_and_user({template_name => "opac-suggestions.tmpl",
-                                                               query => $input,
-                                                               type => "opac",
-                                                               authnotrequired => 1,
-                                                       });
-if (!$borrowernumber) {
-       $borrowernumber = C4::Context->preference("AnonSuggestions");
+if ( C4::Context->preference("AnonSuggestions") ) {
+    ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-suggestions.tmpl",
+            query           => $input,
+            type            => "opac",
+            authnotrequired => 1,
+        }
+    );
+    if ( !$borrowernumber ) {
+        $borrowernumber = C4::Context->preference("AnonSuggestions");
+    }
 }
-} else {
-       ($template, $borrowernumber, $cookie)
-               = get_template_and_user({template_name => "opac-suggestions.tmpl",
-                                                               query => $input,
-                                                               type => "opac",
-                                                               authnotrequired => 1,
-                        });
+else {
+    ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+        {
+            template_name   => "opac-suggestions.tmpl",
+            query           => $input,
+            type            => "opac",
+            authnotrequired => 1,
+        }
+    );
 }
 
-if ($op eq "add_confirm") {
-       &NewSuggestion($borrowernumber,$title,$author,$publishercode,$note,$copyrightdate,$volumedesc,$publicationyear,$place,$isbn,'');
-       # empty fields, to avoid filter in "SearchSuggestion"
-       $title='';
-       $author='';
-       $publishercode='';
-       $copyrightdate ='';
-       $volumedesc = '';
-       $publicationyear = '';
-       $place = '';
-       $isbn = '';
-       $op='else';
+if ( $op eq "add_confirm" ) {
+    &NewSuggestion(
+        $borrowernumber, $title,         $author,     $publishercode,
+        $note,           $copyrightdate, $volumedesc, $publicationyear,
+        $place,          $isbn,          ''
+    );
+
+    # empty fields, to avoid filter in "SearchSuggestion"
+    $title           = '';
+    $author          = '';
+    $publishercode   = '';
+    $copyrightdate   = '';
+    $volumedesc      = '';
+    $publicationyear = '';
+    $place           = '';
+    $isbn            = '';
+    $op              = 'else';
 }
 
-if ($op eq "delete_confirm") {
-       my @delete_field = $input->param("delete_field");
-       foreach my $delete_field (@delete_field) {
-               &DelSuggestion($borrowernumber,$delete_field);
-       }
-       $op='else';
+if ( $op eq "delete_confirm" ) {
+    my @delete_field = $input->param("delete_field");
+    foreach my $delete_field (@delete_field) {
+        &DelSuggestion( $borrowernumber, $delete_field );
+    }
+    $op = 'else';
 }
 
-my $suggestions_loop= &SearchSuggestion($borrowernumber,$author,$title,$publishercode,$status,$suggestedbyme);
-$template->param(suggestions_loop => $suggestions_loop,
-                               title => $title,
-                               author => $author,
-                               publishercode => $publishercode,
-                               status => $status,
-                               suggestedbyme => $suggestedbyme,
-                               "op_$op" => 1,
+my $suggestions_loop =
+  &SearchSuggestion( $borrowernumber, $author, $title, $publishercode, $status,
+    $suggestedbyme );
+$template->param(
+    suggestions_loop => $suggestions_loop,
+    title            => $title,
+    author           => $author,
+    publishercode    => $publishercode,
+    status           => $status,
+    suggestedbyme    => $suggestedbyme,
+    "op_$op"         => 1,
 );
+
 output_html_with_http_headers $input, $cookie, $template->output;
index 188a3bf..ae3ce4b 100755 (executable)
@@ -1,4 +1,22 @@
 #!/usr/bin/perl
+
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+# $Id$
+
 use strict;
 require Exporter;
 use CGI;
@@ -9,41 +27,44 @@ use C4::Circulation::Circ2;
 use C4::Reserves2;
 use C4::Members;
 use C4::Interface::CGI::Output;
-use HTML::Template;
+use C4::Biblio;
 use C4::Date;
 use C4::Letters;
+use C4::Branch; # GetBranches
 
 my $query = new CGI;
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-user.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-user.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
-$borr->{'dateenrolled'} = format_date($borr->{'dateenrolled'});
-$borr->{'expiry'}       = format_date($borr->{'expiry'});
-$borr->{'dateofbirth'}  = format_date($borr->{'dateofbirth'});
-$borr->{'ethnicity'}    = fixEthnicity($borr->{'ethnicity'});
+$borr->{'dateenrolled'} = format_date( $borr->{'dateenrolled'} );
+$borr->{'expiry'}       = format_date( $borr->{'expiry'} );
+$borr->{'dateofbirth'}  = format_date( $borr->{'dateofbirth'} );
+$borr->{'ethnicity'}    = fixEthnicity( $borr->{'ethnicity'} );
 
-if($borr->{'debarred'} || $borr->{'gonenoaddress'} || $borr->{'lost'}){
-       $borr->{'flagged'} =1;
+if ( $borr->{'debarred'} || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
+    $borr->{'flagged'} = 1;
 }
 
-if ($borr->{'amountoutstanding'} > 5) {
+if ( $borr->{'amountoutstanding'} > 5 ) {
     $borr->{'amountoverfive'} = 1;
 }
-if (5 >= $borr->{'amountoutstanding'} && $borr->{'amountoutstanding'} > 0 ) {
+if ( 5 >= $borr->{'amountoutstanding'} && $borr->{'amountoutstanding'} > 0 ) {
     $borr->{'amountoverzero'} = 1;
 }
-if ($borr->{'amountoutstanding'} < 0) {
+if ( $borr->{'amountoutstanding'} < 0 ) {
     $borr->{'amountlessthanzero'} = 1;
-    $borr->{'amountoutstanding'} = -1*($borr->{'amountoutstanding'});
+    $borr->{'amountoutstanding'} = -1 * ( $borr->{'amountoutstanding'} );
 }
 
 $borr->{'amountoutstanding'} = sprintf "%.02f", $borr->{'amountoutstanding'};
@@ -51,106 +72,122 @@ $borr->{'amountoutstanding'} = sprintf "%.02f", $borr->{'amountoutstanding'};
 my @bordat;
 $bordat[0] = $borr;
 
-$template->param(BORROWER_INFO => \@bordat);
-$template->param(borrowernumber => $borrowernumber);
+$template->param( BORROWER_INFO  => \@bordat );
+$template->param( borrowernumber => $borrowernumber );
 
 #get issued items ....
 my $issues = getissues($borr);
 
-my $count = 0;
+my $count          = 0;
 my $overdues_count = 0;
 my @overdues;
 my @issuedat;
-foreach my $key (keys %$issues) {
+my $imgdir = getitemtypeimagesrc();
+my $itemtypes = GetItemTypes();
+foreach my $key ( keys %$issues ) {
     my $issue = $issues->{$key};
-    $issue->{'date_due'}  = format_date($issue->{'date_due'});
+    $issue->{'date_due'} = format_date( $issue->{'date_due'} );
 
     # check for reserves
-    my ($restype, $res) = CheckReserves($issue->{'itemnumber'});
-    if ($restype) {
-       $issue->{'reserved'} = 1;
+    my ( $restype, $res ) = CheckReserves( $issue->{'itemnumber'} );
+    if ( $restype ) {
+        $issue->{'reserved'} = 1;
     }
-
-    my ($numaccts,$accts,$total) = getboracctrecord(undef,$borr);
+    
+    my ( $numaccts, $accts, $total ) = getboracctrecord( undef, $borr );
     my $charges = 0;
     foreach my $ac (@$accts) {
-       if ($ac->{'itemnumber'} == $issue->{'itemnumber'}) {
-           $charges += $ac->{'amountoutstanding'} if $ac->{'accounttype'} eq 'F'; 
-           $charges += $ac->{'amountoutstanding'} if $ac->{'accounttype'} eq 'L';
-       } 
+        if ( $ac->{'itemnumber'} == $issue->{'itemnumber'} ) {
+            $charges += $ac->{'amountoutstanding'}
+              if $ac->{'accounttype'} eq 'F';
+            $charges += $ac->{'amountoutstanding'}
+              if $ac->{'accounttype'} eq 'L';
+        }
     }
     $issue->{'charges'} = $charges;
 
     # get publictype for icon
-    
+
     my $publictype = $issue->{'publictype'};
     $issue->{$publictype} = 1;
 
     # check if item is renewable
     my %env;
-    my $status = renewstatus(\%env,$borrowernumber, $issue->{'itemnumber'});
+    my $status = renewstatus( \%env, $borrowernumber, $issue->{'itemnumber'} );
 
     $issue->{'status'} = $status;
 
-    if ($issue->{'overdue'}) {
-       push @overdues, $issue;
-       $overdues_count++;
-       $issue->{'overdue'} = 1;
-    } else {
-       $issue->{'issued'} = 1;
+    if ( $issue->{'overdue'} ) {
+        push @overdues, $issue;
+        $overdues_count++;
+        $issue->{'overdue'} = 1;
+    }
+    else {
+        $issue->{'issued'} = 1;
+    }
+    # imageurl:
+    my $itemtype = $issue->{'itemtype'};
+    if ( $itemtype ) {
+        $issue->{'imageurl'}    = $imgdir."/".$itemtypes->{$itemtype}->{'imageurl'};
+        $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
     }
     push @issuedat, $issue;
     $count++;
 }
 
-$template->param(ISSUES => \@issuedat);
-$template->param(issues_count => $count);
+$template->param( ISSUES       => \@issuedat );
+$template->param( issues_count => $count );
 
-$template->param(OVERDUES => \@overdues);
-$template->param(overdues_count => $overdues_count);
+$template->param( OVERDUES       => \@overdues );
+$template->param( overdues_count => $overdues_count );
 
 my $branches = GetBranches();
 
 # now the reserved items....
-my ($rcount, $reserves) = FindReserves(undef, $borrowernumber);
+my ( $rcount, $reserves ) = FindReserves( undef, $borrowernumber );
 foreach my $res (@$reserves) {
-    $res->{'reservedate'}  = format_date($res->{'reservedate'});
+    $res->{'reservedate'} = format_date( $res->{'reservedate'} );
     my $publictype = $res->{'publictype'};
     $res->{$publictype} = 1;
     $res->{'waiting'} = 1 if $res->{'found'} eq 'W';
-    $res->{'branch'} = $branches->{$res->{'branchcode'}}->{'branchname'};
+    $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
+    my $biblioData = GetBiblioData($res->{'biblionumber'});
+    $res->{'reserves_title'} = $biblioData->{'title'};
 }
 
-$template->param(RESERVES => $reserves);
-$template->param(reserves_count => $rcount);
+$template->param( RESERVES       => $reserves );
+$template->param( reserves_count => $rcount );
 
 my @waiting;
 my $wcount = 0;
 foreach my $res (@$reserves) {
-    if ($res->{'itemnumber'}) {
-       my $item = getiteminformation('',$res->{'itemnumber'},'');
-       $res->{'holdingbranch'} = $branches->{$item->{'holdingbranch'}}->{'branchname'};
-       $res->{'branch'} = $branches->{$res->{'branchcode'}}->{'branchname'};
-       if($res->{'holdingbranch'} eq $res->{'branch'}){
-                       $res->{'atdestination'} = 1;
-               }
-       push @waiting, $res;
-       $wcount++;
+    if ( $res->{'itemnumber'} ) {
+        my $item = getiteminformation( $res->{'itemnumber'}, '' );
+        $res->{'holdingbranch'} =
+          $branches->{ $item->{'holdingbranch'} }->{'branchname'};
+        $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
+        if ( $res->{'holdingbranch'} eq $res->{'branch'} ) {
+            $res->{'atdestination'} = 1;
+        }
+        my $biblioData = GetBiblioData($res->{'biblionumber'});
+        $res->{'waiting_title'} = $biblioData->{'title'};
+        push @waiting, $res;
+        $wcount++;
     }
 }
-$template->param(WAITING => \@waiting);
+
+$template->param( WAITING => \@waiting );
 
 # current alert subscriptions
-warn " B : $borrowernumber";
 my $alerts = getalert($borrowernumber);
-foreach (@$alerts) {
-       $_->{$_->{type}}=1;
-       $_->{relatedto} = findrelatedto($_->{type},$_->{externalid});
+foreach ( @$alerts ) {
+    $_->{ $_->{type} } = 1;
+    $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
 }
 
-$template->param(waiting_count => $wcount,
-                               textmessaging => $borr->{textmessaging},
-                               OpacPasswordChange => C4::Context->preference("OpacPasswordChange"),
+$template->param(
+    waiting_count      => $wcount,
+    textmessaging      => $borr->{textmessaging},
 );
 
 output_html_with_http_headers $query, $cookie, $template->output;
index 43b7782..d31603c 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-
 use strict;
-require Exporter;
 use CGI;
 
 use C4::Auth;
 use C4::Koha;
 use C4::Circulation::Circ2;
-use C4::Search;
-use HTML::Template;
+
 use C4::Interface::CGI::Output;
 use C4::Date;
 use C4::Members;
 
 my $query = new CGI;
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-userdetails.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-userdetails.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-
-$borr->{'dateenrolled'} = format_date($borr->{'dateenrolled'});
-$borr->{'expiry'}       = format_date($borr->{'expiry'});
-$borr->{'dateofbirth'}  = format_date($borr->{'dateofbirth'});
-$borr->{'ethnicity'}    = fixEthnicity($borr->{'ethnicity'});
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
+$borr->{'dateenrolled'} = format_date( $borr->{'dateenrolled'} );
+$borr->{'dateexpiry'}       = format_date( $borr->{'dateexpiry'} );
+$borr->{'dateofbirth'}  = format_date( $borr->{'dateofbirth'} );
+$borr->{'ethnicity'}    = fixEthnicity( $borr->{'ethnicity'} );
 
 $template->param($borr);
-$template->param(LibraryName => C4::Context->preference("LibraryName"),
-);
 
 output_html_with_http_headers $query, $cookie, $template->output;
 
index 830a6a7..55bbefc 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-
 use strict;
 require Exporter;
 use CGI;
 use Mail::Sendmail;
 
-use C4::Auth;         # checkauth, getborrowernumber.
+use C4::Auth;    # checkauth, getborrowernumber.
 use C4::Context;
 use C4::Koha;
 use C4::Circulation::Circ2;
 use C4::Interface::CGI::Output;
-use HTML::Template;
 use C4::Date;
 use C4::Members;
 
 my $query = new CGI;
 
-my ($template, $borrowernumber, $cookie) 
-    = get_template_and_user({template_name => "opac-userupdate.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 0,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "opac-userupdate.tmpl",
+        query           => $query,
+        type            => "opac",
+        authnotrequired => 0,
+        flagsrequired   => { borrow => 1 },
+        debug           => 1,
+    }
+);
 
 # get borrower information ....
-my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
-
+my ( $borr, $flags ) = getpatroninformation( undef, $borrowernumber );
 
 # handle the new information....
 # collect the form values and send an email.
-my @fields = ('title', 'surname', 'firstname', 'phone', 'faxnumber', 'streetaddress', 'emailaddress', 'city');
+my @fields = (
+    'title',     'surname',       'firstname',    'phone',
+    'fax', 'streetaddress', 'emailaddress', 'city','phonepro',
+);
 my $update;
-my $updateemailaddress= C4::Context->preference('KohaAdminEmailAddress');
-if ($updateemailaddress eq '') {
-    warn "KohaAdminEmailAddress system preference not set.  Couldn't send patron update information for $borr->{'firstname'} $borr->{'surname'} (#$borrowernumber)\n";
-    my($template) = get_template_and_user({template_name => "kohaerror.tmpl",
-                            query => $query,
-                            type => "opac",
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                            debug => 1,
-                            });
-
-    $template->param(errormessage => 'KohaAdminEmailAddress system preference
-    is not set.  Please visit the library to update your user record');
+my $updateemailaddress = C4::Context->preference('KohaAdminEmailAddress');
+if ( $updateemailaddress eq '' ) {
+    warn
+"KohaAdminEmailAddress system preference not set.  Couldn't send patron update information for $borr->{'firstname'} $borr->{'surname'} (#$borrowernumber)\n";
+    my ($template) = get_template_and_user(
+        {
+            template_name   => "kohaerror.tmpl",
+            query           => $query,
+            type            => "opac",
+            authnotrequired => 1,
+            flagsrequired   => { borrow => 1 },
+            debug           => 1,
+        }
+    );
+
+    $template->param(
+        errormessage => 'KohaAdminEmailAddress system preference
+    is not set.  Please visit the library to update your user record'
+    );
 
     output_html_with_http_headers $query, $cookie, $template->output;
     exit;
 }
 
-if ($query->{'title'}) {
+if ( $query->{'title'} ) {
+
     # get all the fields:
     my $message = <<"EOF";
 Borrower $borr->{'cardnumber'}
@@ -77,37 +86,42 @@ Borrower $borr->{'cardnumber'}
 has requested to change her/his personal details.
 Please check these new details and make the changes:
 EOF
-    foreach my $field (@fields){
-       my $newfield = $query->param($field);
-       $message .= "$field : $borr->{$field}  -->  $newfield\n";
+    foreach my $field (@fields) {
+        my $newfield = $query->param($field);
+        $message .= "$field : $borr->{$field}  -->  $newfield\n";
     }
     $message .= "\n\nThanks,\nKoha\n\n";
-    my %mail = ( To      => $updateemailaddress ,
-                From    => $updateemailaddress ,
-                Subject => "User Request for update of Record.",
-                Message => $message );
-    if (sendmail %mail) {
-# do something if it works....
-       warn "Mail sent ok\n";
-       print $query->redirect('/cgi-bin/koha/opac-user.pl');
-       exit;
-    } else {
-# do something if it doesnt work....
+    my %mail = (
+        To      => $updateemailaddress,
+        From    => $updateemailaddress,
+        Subject => "User Request for update of Record.",
+        Message => $message
+    );
+
+    if ( sendmail %mail ) {
+
+        # do something if it works....
+        warn "Mail sent ok\n";
+        print $query->redirect('/cgi-bin/koha/opac-user.pl');
+        exit;
+    }
+    else {
+
+        # do something if it doesnt work....
         warn "Error sending mail: $Mail::Sendmail::error \n";
     }
 }
 
-
-$borr->{'dateenrolled'} = format_date($borr->{'dateenrolled'});
-$borr->{'expiry'}       = format_date($borr->{'expiry'});
-$borr->{'dateofbirth'}  = format_date($borr->{'dateofbirth'});
-$borr->{'ethnicity'}    = fixEthnicity($borr->{'ethnicity'});
-
+$borr->{'dateenrolled'} = format_date( $borr->{'dateenrolled'} );
+$borr->{'expiry'}       = format_date( $borr->{'expiry'} );
+$borr->{'dateofbirth'}  = format_date( $borr->{'dateofbirth'} );
+$borr->{'ethnicity'}    = fixEthnicity( $borr->{'ethnicity'} );
 
 my @bordat;
 $bordat[0] = $borr;
 
-$template->param(BORROWER_INFO => \@bordat,
+$template->param( 
+    BORROWER_INFO => \@bordat
 );
 
 output_html_with_http_headers $query, $cookie, $template->output;
index b715dc3..e4a8ff6 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
+# test comment
+
 use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+
+use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
@@ -39,463 +42,694 @@ plugin that shows a stats on borrowers
 
 =cut
 
-my $input = new CGI;
-my $do_it=$input->param('do_it');
+my $input          = new CGI;
+my $do_it          = $input->param('do_it');
 my $fullreportname = "reports/acquisitions_stats.tmpl";
-my $line = $input->param("Line");
-my $column = $input->param("Column");
-my @filters = $input->param("Filter");
-my $podsp = $input->param("PlacedOnDisplay");
-my $rodsp = $input->param("ReceivedOnDisplay");
-my $calc = $input->param("Cellvalue");
-my $output = $input->param("output");
-my $basename = $input->param("basename");
-my $mime = $input->param("MIME");
-my $del = $input->param("sep");
+my $line           = $input->param("Line");
+my $column         = $input->param("Column");
+my @filters        = $input->param("Filter");
+my $podsp          = $input->param("PlacedOnDisplay");
+my $rodsp          = $input->param("ReceivedOnDisplay");
+my $aodsp          = $input->param("AcquiredOnDisplay");    ##added by mason.
+my $calc           = $input->param("Cellvalue");
+my $output         = $input->param("output");
+my $basename       = $input->param("basename");
+my $mime           = $input->param("MIME");
+my $del            = $input->param("sep");
+
 #warn "calcul : ".$calc;
 my ($template, $borrowernumber, $cookie)
        = get_template_and_user({template_name => $fullreportname,
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
-       my $results = calculate($line, $column, $podsp, $rodsp, $calc, \@filters);
-       if ($output eq "screen"){
-               $template->param(mainloop => $results);
-               output_html_with_http_headers $input, $cookie, $template->output;
-               exit(1);
-       } else {
-               print $input->header(-type => 'application/vnd.sun.xml.calc', 
-                                                        -attachment=>"$basename.csv",
-                                                        -name=>"$basename.csv" );
-               my $cols = @$results[0]->{loopcol};
-               my $lines = @$results[0]->{looprow};
-               my $sep;
-               $sep =C4::Context->preference("delimiter");
-               print @$results[0]->{line} ."/". @$results[0]->{column} .$sep;
-               foreach my $col ( @$cols ) {
-                       print $col->{coltitle}.$sep;
-               }
-               print "Total\n";
-               foreach my $line ( @$lines ) {
-                       my $x = $line->{loopcell};
-                       print $line->{rowtitle}.$sep;
-                       foreach my $cell (@$x) {
-                               print $cell->{value}.$sep;
-                       }
-                       print $line->{totalrow};
-                       print "\n";
-               }
-               print "TOTAL";
-               $cols = @$results[0]->{loopfooter};
-               foreach my $col ( @$cols ) {
-                       print $sep.$col->{totalcol};
-               }
-               print $sep.@$results[0]->{total};
-               exit(1);
-       }
-} else {
-       my $dbh = C4::Context->dbh;
-       my @values;
-       my %labels;
-       my %select;
-       my $req;
-       $req = $dbh->prepare("select distinctrow id,name from aqbooksellers order by name");
-       $req->execute;
-       my @select;
-       push @select,"";
-#      $select{""}="";
-       while (my ($value, $desc) =$req->fetchrow) {
-               push @select, $desc;
-#              $select{$value}=$desc;
-       }
-       my $CGIBookSellers=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@select,
-#                              -labels   => \%select,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       $req = $dbh->prepare( "select distinctrow bookfundid,bookfundname from aqbookfund order by bookfundname");
-       $req->execute;
-       undef @select;
-       undef %select;
-       push @select,"";
-       $select{""}="";
-       while (my ($value,$desc) =$req->fetchrow) {
-               push @select, $value;
-               $select{$value}=$desc;
-       }
-       my $CGIBudget=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@select,
-                               -labels    => \%select,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       $req = $dbh->prepare("select distinctrow sort1 from aqorders where sort1 is not null order by sort1");
-       $req->execute;
-       undef @select;
-       push @select,"";
-       my $hassort1;
-       while (my ($value) =$req->fetchrow) {
-               $hassort1 =1 if ($value);
-               push @select, $value;
-       }
-       my $CGISort1=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@select,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       $req = $dbh->prepare("select distinctrow sort2 from aqorders where sort2 is not null order by sort2");
-       $req->execute;
-       undef @select;
-       push @select,"";
-       my $hassort2;
-       my $hglghtsort2;
-       while (my ($value) =$req->fetchrow) {
-               $hassort2 =1 if ($value);
-               $hglghtsort2= !($hassort1);
-               push @select, $value;
-       }
-       my $CGISort2=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@select,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       my @mime = ( C4::Context->preference("MIME") );
-       foreach my $mime (@mime){
-#              warn "".$mime;
-       }
-       
-       my $CGIextChoice=CGI::scrolling_list(
-                               -name     => 'MIME',
-                               -id       => 'MIME',
-                               -values   => \@mime,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       my @dels = ( C4::Context->preference("delimiter") );
-       my $CGIsepChoice=CGI::scrolling_list(
-                               -name     => 'sep',
-                               -id       => 'sep',
-                               -values   => \@dels,
-                               -size     => 1,
-                               -multiple => 0 );
-       
-       $template->param(
-                                       CGIBookSeller => $CGIBookSellers,
-                                       CGIBudget => $CGIBudget,
-                                       hassort1=> $hassort1,
-                                       hassort2=> $hassort2,
-                                       HlghtSort2 => $hglghtsort2,
-                                       CGISort1 => $CGISort1,
-                                       CGISort2 => $CGISort2,
-                                       CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
-                                       );
 
+    #warn
+"line=$line, col=$column, pod=$podsp, rod=$rodsp, aod=$aodsp, calc=$calc, filters=@filters\n";
+
+    my $results =
+      calculate( $line, $column, $podsp, $rodsp, $aodsp, $calc, \@filters );
+    if ( $output eq "screen" ) {
+        $template->param( mainloop => $results );
+        output_html_with_http_headers $input, $cookie, $template->output;
+        exit(1);
+    }
+    else {
+        print $input->header(
+            -type       => 'application/vnd.sun.xml.calc',
+            -encoding    => 'utf-8',
+            -attachment => "$basename.csv",
+            -name       => "$basename.csv"
+        );
+        my $cols  = @$results[0]->{loopcol};
+        my $lines = @$results[0]->{looprow};
+        my $sep;
+        $sep = C4::Context->preference("delimiter");
+        print @$results[0]->{line} . "/" . @$results[0]->{column} . $sep;
+        foreach my $col (@$cols) {
+            print $col->{coltitle} . $sep;
+        }
+        print "Total\n";
+        foreach my $line (@$lines) {
+            my $x = $line->{loopcell};
+            print $line->{rowtitle} . $sep;
+            foreach my $cell (@$x) {
+                print $cell->{value} . $sep;
+            }
+            print $line->{totalrow};
+            print "\n";
+        }
+        print "TOTAL";
+        $cols = @$results[0]->{loopfooter};
+        foreach my $col (@$cols) {
+            print $sep. $col->{totalcol};
+        }
+        print $sep. @$results[0]->{total};
+        exit(1);
+    }
 }
-output_html_with_http_headers $input, $cookie, $template->output;
+else {
+    my $dbh = C4::Context->dbh;
+    my @values;
+    my %labels;
+    my %select;
+    my $req;
+    $req =
+      $dbh->prepare(
+        "SELECT distinctrow id,name FROM aqbooksellers ORDER BY name");
+    $req->execute;
+    my @select;
+    push @select, "";
+
+    #       $select{""}="";
+    while ( my ( $value, $desc ) = $req->fetchrow ) {
+        push @select, $desc;
+
+        #               $select{$value}=$desc;
+    }
+    my $CGIBookSellers = CGI::scrolling_list(
+        -name   => 'Filter',
+        -id     => 'Filter',
+        -values => \@select,
+
+        #                               -labels   => \%select,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    $req =
+      $dbh->prepare(
+"SELECT DISTINCTROW itemtype,description FROM itemtypes ORDER BY description"
+      );
+    $req->execute;
+    undef @select;
+    undef %select;
+    push @select, "";
+    $select{""} = "";
+    while ( my ( $value, $desc ) = $req->fetchrow ) {
+        push @select, $value;
+        $select{$value} = $desc;
+    }
+    my $CGIItemTypes = CGI::scrolling_list(
+        -name     => 'Filter',
+        -id       => 'Filter',
+        -values   => \@select,
+        -labels   => \%select,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    $req =
+      $dbh->prepare(
+"SELECT DISTINCTROW bookfundid,bookfundname FROM aqbookfund ORDER BY bookfundname"
+      );
+    $req->execute;
+    undef @select;
+    undef %select;
+    push @select, "";
+    $select{""} = "";
+
+    while ( my ( $value, $desc ) = $req->fetchrow ) {
+        push @select, $value;
+        $select{$value} = $desc;
+    }
+    my $CGIBudget = CGI::scrolling_list(
+        -name     => 'Filter',
+        -id       => 'Filter',
+        -values   => \@select,
+        -labels   => \%select,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    $req =
+      $dbh->prepare(
+"SELECT DISTINCTROW sort1 FROM aqorders WHERE sort1 IS NOT NULL ORDER BY sort1"
+      );
+    $req->execute;
+    undef @select;
+    push @select, "";
+    my $hassort1;
+    while ( my ($value) = $req->fetchrow ) {
+        $hassort1 = 1 if ($value);
+        push @select, $value;
+    }
+    my $CGISort1 = CGI::scrolling_list(
+        -name     => 'Filter',
+        -id       => 'Filter',
+        -values   => \@select,
+        -size     => 1,
+        -multiple => 0
+    );
 
+    $req =
+      $dbh->prepare(
+"SELECT DISTINCTROW sort2 FROM aqorders WHERE sort2 IS NOT NULL ORDER BY sort2"
+      );
+    $req->execute;
+    undef @select;
+    push @select, "";
+    my $hassort2;
+    my $hglghtsort2;
 
+    while ( my ($value) = $req->fetchrow ) {
+        $hassort2 = 1 if ($value);
+        $hglghtsort2 = !($hassort1);
+        push @select, $value;
+    }
+    my $CGISort2 = CGI::scrolling_list(
+        -name     => 'Filter',
+        -id       => 'Filter',
+        -values   => \@select,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    my @mime = ( C4::Context->preference("MIME") );
+    foreach my $mime (@mime) {
+
+        #               warn "".$mime;
+    }
+
+    my $CGIextChoice = CGI::scrolling_list(
+        -name     => 'MIME',
+        -id       => 'MIME',
+        -values   => \@mime,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    my @dels         = ( C4::Context->preference("delimiter") );
+    my $CGIsepChoice = CGI::scrolling_list(
+        -name     => 'sep',
+        -id       => 'sep',
+        -values   => \@dels,
+        -size     => 1,
+        -multiple => 0
+    );
+
+    $template->param(
+        CGIBookSeller => $CGIBookSellers,
+        CGIItemType   => $CGIItemTypes,
+        CGIBudget     => $CGIBudget,
+        hassort1      => $hassort1,
+        hassort2      => $hassort2,
+        HlghtSort2    => $hglghtsort2,
+        CGISort1      => $CGISort1,
+        CGISort2      => $CGISort2,
+        CGIextChoice  => $CGIextChoice,
+        CGIsepChoice  => $CGIsepChoice
+    );
+
+}
+output_html_with_http_headers $input, $cookie, $template->output;
 
 sub calculate {
-       my ($line, $column, $podsp, $rodsp, ,$process, $filters) = @_;
-       my @mainloop;
-       my @loopfooter;
-       my @loopcol;
-       my @loopline;
-       my @looprow;
-       my %globalline;
-       my $grantotal =0;
-# extract parameters
-       my $dbh = C4::Context->dbh;
-
-# Filters
-# Checking filters
-#
-       my @loopfilter;
-       for (my $i=0;$i<=7;$i++) {
-               my %cell;
-               if ( @$filters[$i] ) {
-                       if ((($i==1) or ($i==3)) and (@$filters[$i-1])) {
-                               $cell{err} = 1 if (@$filters[$i]<@$filters[$i-1]) ;
-                       }
-                       $cell{filter} .= @$filters[$i];
-                       $cell{crit} .="Placed On From" if ($i==0);
-                       $cell{crit} .="Placed On To" if ($i==1);
-                       $cell{crit} .="Received On From" if ($i==2);
-                       $cell{crit} .="Received On To" if ($i==3);
-                       $cell{crit} .="BookSeller" if ($i==4);
-                       $cell{crit} .="Budget" if ($i==5);
-                       $cell{crit} .="Sort1" if ($i==6);
-                       $cell{crit} .="Sort2" if ($i==7);
-                       push @loopfilter, \%cell;
-               }
-       }
-       
-       my @linefilter;
-#      warn "filtres ".@filters[0];
-#      warn "filtres ".@filters[1];
-#      warn "filtres ".@filters[2];
-#      warn "filtres ".@filters[3];
-       
-       $linefilter[0] = @$filters[0] if ($line =~ /closedate/ )  ;
-       $linefilter[1] = @$filters[1] if ($line =~ /closedate/ )  ;
-       $linefilter[0] = @$filters[2] if ($line =~ /received/ )  ;
-       $linefilter[1] = @$filters[3] if ($line =~ /received/ )  ;
-       $linefilter[0] = @$filters[4] if ($line =~ /bookseller/ )  ;
-       $linefilter[0] = @$filters[5] if ($line =~ /bookfund/ )  ;
-       $linefilter[0] = @$filters[6] if ($line =~ /sort1/ )  ;
-       $linefilter[0] = @$filters[7] if ($line =~ /sort2/ ) ;
-#warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
-# 
-       my @colfilter ;
-       $colfilter[0] = @$filters[0] if ($column =~ /closedate/ ) ;
-       $colfilter[1] = @$filters[1] if ($column =~ /closedate/ ) ;
-       $colfilter[0] = @$filters[2] if ($column =~ /received/ )  ;
-       $colfilter[1] = @$filters[3] if ($column =~ /received/ )  ;
-       $colfilter[0] = @$filters[4] if ($column =~ /bookseller/ );
-       $colfilter[0] = @$filters[5] if ($column =~ /bookfund/ )  ;
-       $colfilter[0] = @$filters[6] if ($column =~ /sort1/ )     ;
-       $colfilter[0] = @$filters[7] if ($column =~ /sort2/ )     ;
-#warn "filtre col ".$colfilter[0]." ".$colfilter[1];
-                                              
-# 1st, loop rows.                             
-       my $linefield;                               
-       if (($line =~/closedate/) and ($podsp == 1)) {
-               #Display by day
-               $linefield .="dayname($line)";  
-       } elsif (($line=~/closedate/) and ($podsp == 2)) {
-               #Display by Month
-               $linefield .="monthname($line)";  
-       } elsif (($line=~/closedate/) and ($podsp == 3)) {
-               #Display by Year
-               $linefield .="Year($line)";
-       } elsif (($line =~/received/) and ($rodsp == 1)) {
-               #Display by day
-               $linefield .="dayname($line)";  
-       } elsif (($line=~/received/) and ($rodsp == 2)) {
-               #Display by Month
-               $linefield .="monthname($line)";  
-       } elsif (($line=~/received/) and ($rodsp == 3)) {
-               #Display by Year
-               $linefield .="Year($line)";
-       } else {
-               $linefield .= $line;
-       }  
-       
-       my $strsth;
-       $strsth .= "select distinctrow $linefield from aqorders, aqbasket,aqorderbreakdown left join aqorderdelivery on (aqorders.ordernumber =aqorderdelivery.ordernumber ) left join aqbooksellers on (aqbasket.booksellerid=aqbooksellers.id) where (aqorders.basketno=aqbasket.basketno) and (aqorderbreakdown.ordernumber=aqorders.ordernumber) and $line is not null ";
-       
-       if ( @linefilter ) {
-               if ($linefilter[1]){
-                       if ($linefilter[0]){
-                               $strsth .= " and $line between ? and ? " ;
-                       } else {
-                               $strsth .= " and $line < ? " ;
-                       }
-               } elsif (($linefilter[0]) and (($line=~/closedate/) or ($line=~/received/))){
-                       $strsth .= " and $line > ? " ;
-               } elsif ($linefilter[0]) {
-                       $linefilter[0] =~ s/\*/%/g;
-                       $strsth .= " and $line LIKE ? " ;
-               }
-       }
-       $strsth .=" group by $linefield";
-       $strsth .=" order by $linefield";
-       warn "". $strsth;
-       
-       my $sth = $dbh->prepare( $strsth );
-       if (( @linefilter ) and ($linefilter[1])){
-               $sth->execute("'".$linefilter[0]."'","'".$linefilter[1]."'");
-       } elsif ($linefilter[0]) {
-               $sth->execute($linefilter[0]);
-       } else {
-               $sth->execute;
-       }
-       
-       while ( my ($celvalue) = $sth->fetchrow) {
-               my %cell;
-               if ($celvalue) {
-                       $cell{rowtitle} = $celvalue;
-#              } else {
-#                      $cell{rowtitle} = "";
-               }
-               $cell{totalrow} = 0;
-               push @loopline, \%cell;
-       }
-
-# 2nd, loop cols.
-       my $colfield;
-       if (($column =~/closedate/) and ($podsp == 1)) {
-               #Display by day
-               $colfield .="dayname($column)";  
-       } elsif (($column=~/closedate/) and ($podsp == 2)) {
-               #Display by Month
-               $colfield .="monthname($column)";  
-       } elsif (($column=~/closedate/) and ($podsp == 3)) {
-               #Display by Year
-               $colfield .="Year($column)";
-       } elsif (($column =~/received/) and ($rodsp == 1)) {
-               #Display by day
-               $colfield .="dayname($column)";  
-       } elsif (($column=~/received/) and ($rodsp == 2)) {
-               #Display by Month
-               $colfield .="monthname($column)";  
-       } elsif (($column=~/received/) and ($rodsp == 3)) {
-               #Display by Year
-               $colfield .="Year($column)";
-       } else {
-               $colfield .= $column;
-       }  
-       
-       my $strsth2;
-       $strsth2 .= "select distinctrow $colfield from aqorders, aqbasket,aqorderbreakdown left join aqorderdelivery on (aqorders.ordernumber =aqorderdelivery.ordernumber ) left join aqbooksellers on (aqbasket.booksellerid=aqbooksellers.id) where (aqorders.basketno=aqbasket.basketno) and (aqorderbreakdown.ordernumber=aqorders.ordernumber) and $column is not null ";
-       
-       if ( @colfilter ) {
-               if ($colfilter[1]){
-                       if ($colfilter[0]){
-                               $strsth2 .= " and $column between ? and ? " ;
-                       } else {
-                               $strsth2 .= " and $column < ? " ;
-                       }
-               } elsif (($colfilter[0]) and (($column=~/closedate/) or ($column=~/received/))){
-                       $strsth2 .= " and $column > ? " ;
-               } elsif ($colfilter[0]) {
-                       $colfilter[0] =~ s/\*/%/g;
-                       $strsth2 .= " and $column LIKE ? " ;
-               }
-       }
-       $strsth2 .=" group by $colfield";
-       $strsth2 .=" order by $colfield";
-       warn "". $strsth2;
-       
-       my $sth2 = $dbh->prepare( $strsth2 );
-       if (( @colfilter ) and ($colfilter[1])){
-               warn "from : ".$colfilter[0]." To  :".$colfilter[1];
-               $sth2->execute("'".$colfilter[0]."'","'".$colfilter[1]."'");
-       } elsif ($colfilter[0]) {
-               $sth2->execute($colfilter[0]);
-       } else {
-               $sth2->execute;
-       }
-
-       while (my ($celvalue) = $sth2->fetchrow) {
-               my %cell;
-               if ($celvalue){
-#              warn "coltitle :".$celvalue;
-                       $cell{coltitle} = $celvalue;
-               }
-               push @loopcol, \%cell;
-       }
-#      warn "fin des titres colonnes";
-
-       my $i=0;
-       my @totalcol;
-       my $hilighted=-1;
-       
-       #Initialization of cell values.....
-       my %table;
-#      warn "init table";
-       foreach my $row ( @loopline ) {
-               foreach my $col ( @loopcol ) {
-#                      warn " init table : $row->{rowtitle} / $col->{coltitle} ";
-                       $table{$row->{rowtitle}}->{$col->{coltitle}}=0;
-               }
-               $table{$row->{rowtitle}}->{totalrow}=0;
-       }
-
-# preparing calculation
-       my $strcalc ;
-       $strcalc .= "SELECT $linefield, $colfield, ";
-       $strcalc .= "COUNT( aqorders.ordernumber ) " if ($process ==1);
-       $strcalc .= "SUM( aqorders.quantity * aqorders.listprice ) " if ($process ==2);
-       $strcalc .= "FROM aqorders, aqbasket,aqorderbreakdown left join aqorderdelivery on (aqorders.ordernumber =aqorderdelivery.ordernumber ) left join aqbooksellers on (aqbasket.booksellerid=aqbooksellers.id) where (aqorders.basketno=aqbasket.basketno) and (aqorderbreakdown.ordernumber=aqorders.ordernumber) ";
-
-       @$filters[0]=~ s/\*/%/g if (@$filters[0]);
-       $strcalc .= " AND aqbasket.closedate > '" . @$filters[0] ."'" if ( @$filters[0] );
-       @$filters[1]=~ s/\*/%/g if (@$filters[1]);
-       $strcalc .= " AND aqbasket.closedate < '" . @$filters[1] ."'" if ( @$filters[1] );
-       @$filters[2]=~ s/\*/%/g if (@$filters[2]);
-       $strcalc .= " AND aqorderdelivery.deliverydate > '" . @$filters[2] ."'" if ( @$filters[2] );
-       @$filters[3]=~ s/\*/%/g if (@$filters[3]);
-       $strcalc .= " AND aqorderdelivery.deliverydate < '" . @$filters[3] ."'" if ( @$filters[3] );
-       @$filters[4]=~ s/\*/%/g if (@$filters[4]);
-       $strcalc .= " AND aqbooksellers.name like '" . @$filters[4] ."'" if ( @$filters[4] );
-       @$filters[5]=~ s/\*/%/g if (@$filters[5]);
-       $strcalc .= " AND aqbookfund.bookfundid like '" . @$filters[5] ."'" if ( @$filters[5] );
-       @$filters[6]=~ s/\*/%/g if (@$filters[6]);
-       $strcalc .= " AND aqorders.sort1 like '" . @$filters[6] ."'" if ( @$filters[6] );
-       @$filters[7]=~ s/\*/%/g if (@$filters[7]);
-       $strcalc .= " AND aqorders.sort2 like '" . @$filters[7] ."'" if ( @$filters[7] );
-       $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
-       warn "". $strcalc;
-       my $dbcalc = $dbh->prepare($strcalc);
-       $dbcalc->execute;
-
-#      warn "filling table";
-       my $emptycol; 
-       while (my ($row, $col, $value) = $dbcalc->fetchrow) {
-#              warn "filling table $row / $col / $value ";
-               $emptycol = 1 if ($col eq undef);
-               $col = "zzEMPTY" if ($col eq undef);
-               $row = "zzEMPTY" if ($row eq undef);
-               
-               $table{$row}->{$col}+=$value;
-               $table{$row}->{totalrow}+=$value;
-               $grantotal += $value;
-       }
-
-       push @loopcol,{coltitle => "NULL"} if ($emptycol);
-       
-       foreach my $row ( sort keys %table ) {
-               my @loopcell;
-               #@loopcol ensures the order for columns is common with column titles
-               # and the number matches the number of columns
-               foreach my $col ( @loopcol ) {
-                       my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
-                       push @loopcell, {value => $value  } ;
-               }
-               push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
-                                               'loopcell' => \@loopcell,
-                                               'hilighted' => ($hilighted >0),
-                                               'totalrow' => $table{$row}->{totalrow}
-                                       };
-               $hilighted = -$hilighted;
-       }
-       
-#      warn "footer processing";
-       foreach my $col ( @loopcol ) {
-               my $total=0;
-               foreach my $row ( @looprow ) {
-                       $total += $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
-#                      warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
-               }
-#              warn "summ for column ".$col->{coltitle}."  = ".$total;
-               push @loopfooter, {'totalcol' => $total};
-       }
-                       
-
-       # the header of the table
-       $globalline{loopfilter}=\@loopfilter;
-       # the core of the table
-       $globalline{looprow} = \@looprow;
-       $globalline{loopcol} = \@loopcol;
-#      # the foot (totals by borrower type)
-       $globalline{loopfooter} = \@loopfooter;
-       $globalline{total}= $grantotal;
-       $globalline{line} = $line;
-       $globalline{column} = $column;
-       push @mainloop,\%globalline;
-       return \@mainloop;
+    my ( $line, $column, $podsp, $rodsp, $aodsp, $process, $filters ) = @_;
+    my @mainloop;
+    my @loopfooter;
+    my @loopcol;
+    my @loopline;
+    my @looprow;
+    my %globalline;
+    my $grantotal = 0;
+
+    # extract parameters
+    my $dbh = C4::Context->dbh;
+
+    # Filters
+    # Checking filters
+    #
+    my @loopfilter;
+    for ( my $i = 0 ; $i <= 8 ; $i++ ) {
+        my %cell;
+        if ( @$filters[$i] ) {
+            if ( ( ( $i == 1 ) or ( $i == 3 ) ) and ( @$filters[ $i - 1 ] ) ) {
+                $cell{err} = 1 if ( @$filters[$i] < @$filters[ $i - 1 ] );
+            }
+            $cell{filter} .= @$filters[$i];
+            $cell{crit}   .= "Placed On From" if ( $i == 0 );
+            $cell{crit}   .= "Placed On To" if ( $i == 1 );
+            $cell{crit}   .= "Received On From" if ( $i == 2 );
+            $cell{crit}   .= "Received On To" if ( $i == 3 );
+
+            $cell{crit} .= "Acquired On From" if ( $i == 4 );
+            $cell{crit} .= "Acquired On To"   if ( $i == 5 );
+
+            $cell{crit} .= "BookSeller" if ( $i == 6 );
+            $cell{crit} .= "Doc Type"   if ( $i == 7 );
+            $cell{crit} .= "Budget"     if ( $i == 8 );
+            $cell{crit} .= "Sort1"      if ( $i == 9 );
+            $cell{crit} .= "Sort2"      if ( $i == 10 );
+            push @loopfilter, \%cell;
+        }
+    }
+
+    my @linefilter;
+
+    #       warn "filtres ".@filters[0];
+    #       warn "filtres ".@filters[1];
+    #       warn "filtres ".@filters[2];
+    #       warn "filtres ".@filters[3];
+
+    $linefilter[0] = @$filters[0] if ( $line =~ /closedate/ );
+    $linefilter[1] = @$filters[1] if ( $line =~ /closedate/ );
+    $linefilter[0] = @$filters[2] if ( $line =~ /received/ );
+    $linefilter[1] = @$filters[3] if ( $line =~ /received/ );
+
+    $linefilter[0] = @$filters[4] if ( $line =~ /acquired/ );
+    $linefilter[1] = @$filters[5] if ( $line =~ /acquired/ );
+
+    $linefilter[0] = @$filters[6]  if ( $line =~ /bookseller/ );
+    $linefilter[0] = @$filters[7]  if ( $line =~ /itemtype/ );
+    $linefilter[0] = @$filters[8]  if ( $line =~ /bookfund/ );
+    $linefilter[0] = @$filters[9]  if ( $line =~ /sort1/ );
+    $linefilter[0] = @$filters[10] if ( $line =~ /sort2/ );
+
+    #warn "filtre lignes".$linefilter[0]." ".$linefilter[1];
+    #
+    my @colfilter;
+    $colfilter[0] = @$filters[0] if ( $column =~ /closedate/ );
+    $colfilter[1] = @$filters[1] if ( $column =~ /closedate/ );
+    $colfilter[0] = @$filters[2] if ( $column =~ /received/ );
+    $colfilter[1] = @$filters[3] if ( $column =~ /received/ );
+
+    $colfilter[0] = @$filters[4] if ( $column =~ /acquired/ );
+    $colfilter[1] = @$filters[5] if ( $column =~ /acquired/ );
+
+    $colfilter[0] = @$filters[6]  if ( $column =~ /bookseller/ );
+    $colfilter[0] = @$filters[7]  if ( $column =~ /itemtype/ );
+    $colfilter[0] = @$filters[8]  if ( $column =~ /bookfund/ );
+    $colfilter[0] = @$filters[9]  if ( $column =~ /sort1/ );
+    $colfilter[0] = @$filters[10] if ( $column =~ /sort2/ );
+
+    #warn "filtre col ".$colfilter[0]." ".$colfilter[1];
+
+    #warn "line=$line, podsp=$podsp, rodsp=$rodsp, aodsp=$aodsp\n";
+
+    # 1st, loop rows.
+    my $linefield;
+    if ( ( $line =~ /closedate/ ) and ( $podsp == 1 ) ) {
+
+        #Display by day
+        $linefield .= "dayname($line)";
+    }
+    elsif ( ( $line =~ /closedate/ ) and ( $podsp == 2 ) ) {
+
+        #Display by Month
+        $linefield .= "monthname($line)";
+    }
+    elsif ( ( $line =~ /closedate/ ) and ( $podsp == 3 ) ) {
+
+        #Display by Year
+        $linefield .= "Year($line)";
+
+    }
+    elsif ( ( $line =~ /received/ ) and ( $rodsp == 1 ) ) {
+
+        #Display by day
+        $linefield .= "dayname($line)";
+    }
+    elsif ( ( $line =~ /received/ ) and ( $rodsp == 2 ) ) {
+
+        #Display by Month
+        $linefield .= "monthname($line)";
+    }
+    elsif ( ( $line =~ /received/ ) and ( $rodsp == 3 ) ) {
+
+        #Display by Year
+        $linefield .= "Year($line)";
+
+    }
+    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 1 ) ) {
+
+        #Display by day
+        $linefield .= "dayname($line)";
+    }
+    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 2 ) ) {
+
+        #Display by Month
+        $linefield .= "monthname($line)";
+    }
+    elsif ( ( $line =~ /acquired/ ) and ( $aodsp == 3 ) ) {
+
+        #Display by Year
+        $linefield .= "Year($line)";
+
+    }
+    else {
+        $linefield .= $line;
+    }
+
+    my $strsth;
+    $strsth .=
+      "SELECT DISTINCTROW $linefield FROM (aqorders, aqbasket,aqorderbreakdown)
+                LEFT JOIN items ON (aqorders.biblioitemnumber= items.biblioitemnumber)
+                LEFT JOIN biblioitems ON (aqorders.biblioitemnumber= biblioitems.biblioitemnumber)
+                LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
+                LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id) WHERE (aqorders.basketno=aqbasket.basketno)
+                AND (aqorderbreakdown.ordernumber=aqorders.ordernumber) AND $line IS NOT NULL ";
+
+    if (@linefilter) {
+        if ( $linefilter[1] ) {
+            if ( $linefilter[0] ) {
+                $strsth .= " AND $line BETWEEN ? AND ? ";
+            }
+            else {
+                $strsth .= " AND $line < ? ";
+            }
+        }
+        elsif (
+            ( $linefilter[0] )
+            and (  ( $line =~ /closedate/ )
+                or ( $line =~ /received/ )
+                or ( $line =~ /acquired/ ) )
+          )
+        {
+            $strsth .= " AND $line > ? ";
+        }
+        elsif ( $linefilter[0] ) {
+            $linefilter[0] =~ s/\*/%/g;
+            $strsth .= " AND $line LIKE ? ";
+        }
+    }
+    $strsth .= " GROUP BY $linefield";
+    $strsth .= " ORDER BY $linefield";
+
+    #warn "377:strsth= $strsth";
+
+    my $sth = $dbh->prepare($strsth);
+    if ( (@linefilter) and ( $linefilter[1] ) ) {
+        $sth->execute( "'" . $linefilter[0] . "'", "'" . $linefilter[1] . "'" );
+    }
+    elsif ( $linefilter[0] ) {
+        $sth->execute( $linefilter[0] );
+    }
+    else {
+        $sth->execute;
+    }
+
+    while ( my ($celvalue) = $sth->fetchrow ) {
+        my %cell;
+        if ($celvalue) {
+            $cell{rowtitle} = $celvalue;
+
+            #               } else {
+            #                       $cell{rowtitle} = "";
+        }
+        $cell{totalrow} = 0;
+        push @loopline, \%cell;
+    }
+
+    #warn "column=$column, podsp=$podsp, rodsp=$rodsp, aodsp=$aodsp\n";
+
+    # 2nd, loop cols.
+    my $colfield;
+    if ( ( $column =~ /closedate/ ) and ( $podsp == 1 ) ) {
+
+        #Display by day
+        $colfield .= "dayname($column)";
+    }
+    elsif ( ( $column =~ /closedate/ ) and ( $podsp == 2 ) ) {
+
+        #Display by Month
+        $colfield .= "monthname($column)";
+    }
+    elsif ( ( $column =~ /closedate/ ) and ( $podsp == 3 ) ) {
+
+        #Display by Year
+        $colfield .= "Year($column)";
+
+    }
+    elsif ( ( $column =~ /deliverydate/ ) and ( $rodsp == 1 ) ) {
+
+        #Display by day
+        $colfield .= "dayname($column)";
+    }
+    elsif ( ( $column =~ /deliverydate/ ) and ( $rodsp == 2 ) ) {
+
+        #Display by Month
+        $colfield .= "monthname($column)";
+    }
+    elsif ( ( $column =~ /deliverydate/ ) and ( $rodsp == 3 ) ) {
+
+        #Display by Year
+        $colfield .= "Year($column)";
+
+    }
+    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 1 ) ) {
+
+        #Display by day
+        $colfield .= "dayname($column)";
+    }
+    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 2 ) ) {
+
+        #Display by Month
+        $colfield .= "monthname($column)";
+    }
+    elsif ( ( $column =~ /dateaccessioned/ ) and ( $aodsp == 3 ) ) {
+
+        #Display by Year
+        $colfield .= "Year($column)";
+
+    }
+    else {
+        $colfield .= $column;
+    }
+
+    my $strsth2;
+    $strsth2 .=
+      "SELECT distinctrow $colfield FROM (aqorders, aqbasket,aqorderbreakdown)
+                 LEFT JOIN items ON (aqorders.biblioitemnumber= items.biblioitemnumber)
+                 LEFT JOIN biblioitems ON (aqorders.biblioitemnumber= biblioitems.biblioitemnumber)
+                 LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
+                 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id)
+                 WHERE (aqorders.basketno=aqbasket.basketno) AND (aqorderbreakdown.ordernumber=aqorders.ordernumber)
+                 AND $column IS NOT NULL";
+
+    if (@colfilter) {
+        if ( $colfilter[1] ) {
+            if ( $colfilter[0] ) {
+                $strsth2 .= " AND $column BETWEEN  ? AND ? ";
+            }
+            else {
+                $strsth2 .= " AND $column < ? ";
+            }
+        }
+        elsif (
+            ( $colfilter[0] )
+            and (  ( $column =~ /closedate/ )
+                or ( $line =~ /received/ )
+                or ( $line =~ /acquired/ ) )
+          )
+        {
+            $strsth2 .= " AND $column > ? ";
+        }
+        elsif ( $colfilter[0] ) {
+            $colfilter[0] =~ s/\*/%/g;
+            $strsth2 .= " AND $column LIKE ? ";
+        }
+    }
+    $strsth2 .= " GROUP BY $colfield";
+    $strsth2 .= " ORDER BY $colfield";
+
+    #        warn "MASON:. $strsth2";
+
+    my $sth2 = $dbh->prepare($strsth2);
+    if ( (@colfilter) and ( $colfilter[1] ) ) {
+
+        #                warn "from : ".$colfilter[0]." To  :".$colfilter[1];
+        $sth2->execute( "'" . $colfilter[0] . "'", "'" . $colfilter[1] . "'" );
+    }
+    elsif ( $colfilter[0] ) {
+        $sth2->execute( $colfilter[0] );
+    }
+    else {
+        $sth2->execute;
+    }
+
+    while ( my ($celvalue) = $sth2->fetchrow ) {
+        my %cell;
+        if ($celvalue) {
+
+            #               warn "coltitle :".$celvalue;
+            $cell{coltitle} = $celvalue;
+        }
+        push @loopcol, \%cell;
+    }
+
+    #       warn "fin des titres colonnes";
+
+    my $i = 0;
+    my @totalcol;
+    my $hilighted = -1;
+
+    #Initialization of cell values.....
+    my %table;
+
+    #       warn "init table";
+    foreach my $row (@loopline) {
+        foreach my $col (@loopcol) {
+
+#                       warn " init table : $row->{rowtitle} / $col->{coltitle} ";
+            $table{ $row->{rowtitle} }->{ $col->{coltitle} } = 0;
+        }
+        $table{ $row->{rowtitle} }->{totalrow} = 0;
+    }
+
+    # preparing calculation
+    my $strcalc;
+    $strcalc .= "SELECT $linefield, $colfield, ";
+    $strcalc .= "SUM( aqorders.quantity ) " if ( $process == 1 );
+    $strcalc .= "SUM( aqorders.quantity * aqorders.listprice ) "
+      if ( $process == 2 );
+    $strcalc .= "FROM (aqorders, aqbasket,aqorderbreakdown)
+                 LEFT JOIN items ON (aqorders.biblioitemnumber= items.biblioitemnumber)
+                 LEFT JOIN biblioitems ON (aqorders.biblioitemnumber= biblioitems.biblioitemnumber)
+                 LEFT JOIN aqorderdelivery ON (aqorders.ordernumber =aqorderdelivery.ordernumber )
+                 LEFT JOIN aqbooksellers ON (aqbasket.booksellerid=aqbooksellers.id) WHERE (aqorders.basketno=aqbasket.basketno)
+                      AND (aqorderbreakdown.ordernumber=aqorders.ordernumber) ";
+
+    @$filters[0] =~ s/\*/%/g if ( @$filters[0] );
+    $strcalc .= " AND aqbasket.closedate > '" . @$filters[0] . "'"
+      if ( @$filters[0] );
+    @$filters[1] =~ s/\*/%/g if ( @$filters[1] );
+    $strcalc .= " AND aqbasket.closedate < '" . @$filters[1] . "'"
+      if ( @$filters[1] );
+    @$filters[2] =~ s/\*/%/g if ( @$filters[2] );
+    $strcalc .= " AND aqorderdelivery.deliverydate > '" . @$filters[2] . "'"
+      if ( @$filters[2] );
+    @$filters[3] =~ s/\*/%/g if ( @$filters[3] );
+    $strcalc .= " AND aqorderdelivery.deliverydate < '" . @$filters[3] . "'"
+      if ( @$filters[3] );
+    @$filters[4] =~ s/\*/%/g if ( @$filters[4] );
+    $strcalc .= " AND aqbasket.closedate > '" . @$filters[4] . "'"
+      if ( @$filters[4] );
+    @$filters[5] =~ s/\*/%/g if ( @$filters[5] );
+    $strcalc .= " AND aqbasket.closedate < '" . @$filters[5] . "'"
+      if ( @$filters[5] );
+    @$filters[6] =~ s/\*/%/g if ( @$filters[6] );
+    $strcalc .= " AND aqbooksellers.name LIKE '" . @$filters[6] . "'"
+      if ( @$filters[6] );
+    @$filters[7] =~ s/\*/%/g if ( @$filters[7] );
+    $strcalc .= " AND biblioitems.itemtype LIKE '" . @$filters[7] . "'"
+      if ( @$filters[7] );
+    @$filters[8] =~ s/\*/%/g if ( @$filters[8] );
+    $strcalc .= " AND aqbookfund.bookfundid LIKE '" . @$filters[8] . "'"
+      if ( @$filters[8] );
+    @$filters[9] =~ s/\*/%/g if ( @$filters[9] );
+    $strcalc .= " AND aqorders.sort1 LIKE '" . @$filters[9] . "'"
+      if ( @$filters[9] );
+    @$filters[10] =~ s/\*/%/g if ( @$filters[10] );
+    $strcalc .= " AND aqorders.sort2 LIKE '" . @$filters[10] . "'"
+      if ( @$filters[10] );
+    $strcalc .= " GROUP BY $linefield, $colfield ORDER BY $linefield,$colfield";
+
+    #        warn "/n/n". $strcalc;
+    my $dbcalc = $dbh->prepare($strcalc);
+    $dbcalc->execute;
+
+    #       warn "filling table";
+    my $emptycol;
+    while ( my ( $row, $col, $value ) = $dbcalc->fetchrow ) {
+
+        #              warn "filling table $row / $col / $value ";
+        $emptycol = 1         if ( $col eq undef );
+        $col      = "zzEMPTY" if ( $col eq undef );
+        $row      = "zzEMPTY" if ( $row eq undef );
+
+        $table{$row}->{$col}     += $value;
+        $table{$row}->{totalrow} += $value;
+        $grantotal               += $value;
+    }
+
+    push @loopcol, { coltitle => "NULL" } if ($emptycol);
+
+    foreach my $row ( sort keys %table ) {
+        my @loopcell;
+
+        #@loopcol ensures the order for columns is common with column titles
+        # and the number matches the number of columns
+        foreach my $col (@loopcol) {
+            my $value = $table{$row}->{
+                ( $col->{coltitle} eq "NULL" )
+                ? "zzEMPTY"
+                : $col->{coltitle}
+              };
+            push @loopcell, { value => $value };
+        }
+        push @looprow,
+          {
+            'rowtitle' => ( $row eq "zzEMPTY" ) ? "NULL" : $row,
+            'loopcell'  => \@loopcell,
+            'hilighted' => ( $hilighted > 0 ),
+            'totalrow'  => $table{$row}->{totalrow}
+          };
+        $hilighted = -$hilighted;
+    }
+
+    #       warn "footer processing";
+    foreach my $col (@loopcol) {
+        my $total = 0;
+        foreach my $row (@looprow) {
+            $total += $table{
+                ( $row->{rowtitle} eq "NULL" ) ? "zzEMPTY"
+                : $row->{rowtitle}
+              }->{
+                ( $col->{coltitle} eq "NULL" ) ? "zzEMPTY"
+                : $col->{coltitle}
+              };
+
+#                       warn "value added ".$table{$row->{rowtitle}}->{$col->{coltitle}}. "for line ".$row->{rowtitle};
+        }
+
+        #               warn "summ for column ".$col->{coltitle}."  = ".$total;
+        push @loopfooter, { 'totalcol' => $total };
+    }
+
+    # the header of the table
+    #        $globalline{loopfilter}=\@loopfilter;
+    # the core of the table
+    $globalline{looprow} = \@looprow;
+    $globalline{loopcol} = \@loopcol;
+
+    #       # the foot (totals by borrower type)
+    $globalline{loopfooter} = \@loopfooter;
+    $globalline{total}      = $grantotal;
+    $globalline{line}       = $line;
+    $globalline{column}     = $column;
+    push @mainloop, \%globalline;
+    return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
+
index c62aebe..cd1ce60 100755 (executable)
@@ -23,11 +23,13 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+use C4::Branch; # GetBranches
+use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 use Date::Manip;
+use C4::Members;
 
 =head1 NAME
 
@@ -56,10 +58,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($limit, $column, \@filters);
@@ -71,6 +77,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -130,10 +137,50 @@ if ($do_it) {
                                -values   => \@dels,
                                -size     => 1,
                                -multiple => 0 );
+       #branch
+       my $branches = GetBranches;
+       my @branchloop;
+       foreach my $thisbranch (keys %$branches) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisbranch,
+#                                                                      selected => $selected,
+                                                                       branchname => $branches->{$thisbranch}->{'branchname'},
+                                                       );
+                       push @branchloop, \%row;
+       }
+
+       #doctype
+       my $itemtypes = GetItemTypes;
+       my @itemtypeloop;
+       foreach my $thisitemtype (keys %$itemtypes) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisitemtype,
+#                                                                      selected => $selected,
+                                                                       description => $itemtypes->{$thisitemtype}->{'description'},
+                                                       );
+                       push @itemtypeloop, \%row;
+       }
+       
+       #borcat
+       my ($codes,$labels) = GetborCatFromCatType(undef,undef);
+       my @borcatloop;
+       foreach my $thisborcat (sort keys %$labels) {
+ #                     my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisborcat,
+ #                                                                     selected => $selected,
+                                                                       description => $labels->{$thisborcat},
+                                                       );
+                       push @borcatloop, \%row;
+       }
        
+       #Day
+       #Month
        $template->param(
                                        CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
+                                       CGIsepChoice => $CGIsepChoice,
+                                       branchloop =>\@branchloop,
+                                       itemtypeloop =>\@itemtypeloop,
+                                       borcatloop =>\@borcatloop,
                                        );
 output_html_with_http_headers $input, $cookie, $template->output;
 }
@@ -241,7 +288,7 @@ sub calculate {
        
                while (my ($celvalue) = $sth2->fetchrow) {
                        my %cell;
-                       $cell{coltitle} = $celvalue;
+                       $cell{'coltitle'} = ($celvalue?$celvalue:"NULL");
                        push @loopcol, \%cell;
                }
        #       warn "fin des titres colonnes";
@@ -294,31 +341,29 @@ sub calculate {
        
        $strcalc .= " group by borrowers.borrowernumber";
        $strcalc .= ", $colfield" if ($column);
-       $strcalc .= " order by ";
-       $strcalc .= "$colfield, " if ($colfield);
-       $strcalc .= "RANK DESC ";
-       my $max;
-       if (@loopcol) {
-               $max = $line*@loopcol;
-       } else { $max=$line;}
-       $strcalc .= " LIMIT 0,$max";
+       $strcalc .= " order by RANK DESC";
+       $strcalc .= ",$colfield " if ($colfield);
+#      my $max;
+#      if (@loopcol) {
+#              $max = $line*@loopcol;
+#      } else { $max=$line;}
+#      $strcalc .= " LIMIT 0,$max";
        warn "SQL :". $strcalc;
        
        my $dbcalc = $dbh->prepare($strcalc);
        $dbcalc->execute;
 #      warn "filling table";
        my $previous_col;
-       my $i=1;
+       my %indice;
        while (my  @data = $dbcalc->fetchrow) {
                my ($row, $rank, $id, $col )=@data;
                $col = "zzEMPTY" if ($col eq undef);
-               $i=1 if (($previous_col) and not($col eq $previous_col));
-               $table[$i]->{$col}->{'name'}=$row;
-               $table[$i]->{$col}->{'count'}=$rank;
-               $table[$i]->{$col}->{'link'}=$id;
-               warn " ".$i." ".$col. " ".$row;
-               $i++;
-               $previous_col=$col;
+               $indice{$col}=1 if (not($indice{$col}));
+               $table[$indice{$col}]->{$col}->{'name'}=$row;
+               $table[$indice{$col}]->{$col}->{'count'}=$rank;
+               $table[$indice{$col}]->{$col}->{'link'}=$id;
+#              warn " ".$i." ".$col. " ".$row;
+               $indice{$col}++;
        }
        
        push @loopcol,{coltitle => "Global"} if not($column);
@@ -326,7 +371,7 @@ sub calculate {
        for ($i=1; $i<=$line;$i++) {
                my @loopcell;
                warn " $i";
-               #@loopcol ensures the order for columns is common with column titles
+               #@loborrowersopcol ensures the order for columns is common with column titles
                # and the number matches the number of columns
                my $colcount=0;
                foreach my $col ( @loopcol ) {
@@ -369,4 +414,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index abbb998..8145519 100755 (executable)
@@ -23,11 +23,13 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+
+use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 use Date::Manip;
+use C4::Members;
 
 =head1 NAME
 
@@ -56,10 +58,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($limit, $column, \@filters);
@@ -71,6 +77,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -131,9 +138,22 @@ if ($do_it) {
                                -size     => 1,
                                -multiple => 0 );
        
+       my ($codes,$labels) = GetborCatFromCatType(undef,undef);
+       my @borcatloop;
+       foreach my $thisborcat (sort keys %$labels) {
+ #                     my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisborcat,
+ #                                                                     selected => $selected,
+                                                                       description => $labels->{$thisborcat},
+                                                       );
+                       push @borcatloop, \%row;
+       }
+       
+       
        $template->param(
                                        CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
+                                       CGIsepChoice => $CGIsepChoice,
+                                       borcatloop =>\@borcatloop,
                                        );
 output_html_with_http_headers $input, $cookie, $template->output;
 }
@@ -157,7 +177,7 @@ sub calculate {
 # Checking filters
 #
        my @loopfilter;
-       for (my $i=0;$i<=6;$i++) {
+       for (my $i=0;$i<=2;$i++) {
                my %cell;
                if ( @$filters[$i] ) {
                        if (($i==1) and (@$filters[$i-1])) {
@@ -165,6 +185,7 @@ sub calculate {
                        }
                        $cell{filter} .= @$filters[$i];
                        $cell{crit} .="Bor Cat" if ($i==0);
+                       $cell{crit} .="Without issues since" if ($i==1);
                        push @loopfilter, \%cell;
                }
        }
@@ -226,13 +247,31 @@ sub calculate {
 # preparing calculation
        my $strcalc ;
        
-# Processing average loanperiods
+# Processing calculation
        $strcalc .= "SELECT CONCAT( borrowers.surname , \"\\t\",borrowers.firstname, \"\\t\", borrowers.cardnumber)";
        $strcalc .= " , $colfield " if ($colfield);
-       $strcalc .= " FROM borrowers LEFT JOIN issues ON  issues.borrowernumber=borrowers.borrowernumber WHERE issues.borrowernumber is null";
+       $strcalc .= " FROM borrowers ";
+       $strcalc .= "WHERE 1 ";
        @$filters[0]=~ s/\*/%/g if (@$filters[0]);
        $strcalc .= " AND borrowers.categorycode like '" . @$filters[0] ."'" if ( @$filters[0] );
-       
+       if (@$filters[1]){
+               my $strqueryfilter="SELECT DISTINCT borrowernumber FROM issues where issues.timestamp> @$filters[1] ";
+               my $queryfilter = $dbh->prepare("SELECT DISTINCT borrowernumber FROM issues where issues.timestamp> @$filters[1] ");
+               $strcalc .= " AND borrowers.borrowernumber not in ($strqueryfilter)";
+               
+#              $queryfilter->execute(@$filters[1]);
+#              while (my ($borrowernumber)=$queryfilter->fetchrow){
+#                      $strcalc .= " AND borrowers.borrowernumber <> $borrowernumber ";
+#              }
+       } else {
+               my $strqueryfilter="SELECT DISTINCT borrowernumber FROM issues ";
+               my $queryfilter = $dbh->prepare("SELECT DISTINCT borrowernumber FROM issues ");
+               $queryfilter->execute;
+               $strcalc .= " AND borrowers.borrowernumber not in ($strqueryfilter)";
+#              while (my ($borrowernumber)=$queryfilter->fetchrow){
+#                      $strcalc .= " AND borrowers.borrowernumber <> $borrowernumber ";
+#              }
+       }
        $strcalc .= " group by borrowers.borrowernumber";
        $strcalc .= ", $colfield" if ($column);
        $strcalc .= " order by $colfield " if ($colfield);
@@ -260,7 +299,7 @@ sub calculate {
        
        push @loopcol,{coltitle => "Global"} if not($column);
        
-       my $max =(($line)?$line:@table);
+       my $max =(($line)?$line:@table -1);
        for ($i=1; $i<=$max;$i++) {
                my @loopcell;
                #@loopcol ensures the order for columns is common with column titles
@@ -298,4 +337,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index d08842e..218cc27 100755 (executable)
@@ -23,8 +23,10 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+use C4::Branch; # GetBranches
+use C4::Output;
 use C4::Koha;
+use C4::Acquisition;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 
@@ -57,7 +59,7 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports=> 1},
                                debug => 1,
                                });
 $template->param(do_it => $do_it);
@@ -69,8 +71,9 @@ if ($do_it) {
                exit(1);
        } else {
                print $input->header(-type => 'application/vnd.sun.xml.calc',
-                                                        -name=>"$basename.csv",
-                                                        -attachment=>"$basename.csv");
+                                     -encoding    => 'utf-8',
+                                     -name=>"$basename.csv",
+                                     -attachment=>"$basename.csv");
                my $cols = @$results[0]->{loopcol};
                my $lines = @$results[0]->{looprow};
                my $sep;
@@ -119,6 +122,17 @@ if ($do_it) {
                                -size     => 1,
                                -multiple => 0 );
        
+my $branches = GetBranches;
+my @branchloop;
+foreach my $thisbranch (keys %$branches) {
+   # my $selected = 1 if $thisbranch eq $branch;
+    my %row =(value => $thisbranch,
+#                selected => $selected,
+                branchname => $branches->{$thisbranch}->{'branchname'},
+            );
+    push @branchloop, \%row;
+}
+       
        $req = $dbh->prepare( "select distinctrow sort1 from borrowers order by sort1");
        $req->execute;
        my @select_sort1;
@@ -172,13 +186,14 @@ if ($do_it) {
                                -values   => \@dels,
                                -size     => 1,
                                -multiple => 0 );
-       $template->param(CGICatCode => $CGICatCode,
+       $template->param(CGICatcode => $CGICatCode,
                                        CGISort1 => $CGIsort1,
                                        hassort1 => $hassort1,
                                        CGISort2 => $CGIsort2,
                                        hassort2 => $hassort2,
                                        CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
+                                       CGIsepChoice => $CGIsepChoice,
+                                       CGIBranch => @branchloop
                                        );
 
 }
@@ -207,14 +222,16 @@ sub calculate {
        
        $linefilter = @$filters[0] if ($line =~ /categorycode/ )  ;
        $linefilter = @$filters[1] if ($line =~ /zipcode/ )  ;
-       $linefilter = @$filters[2] if ($line =~ /sort1/ ) ;
-       $linefilter = @$filters[3] if ($line =~ /sort2/ ) ;
+       $linefilter = @$filters[2] if ($line =~ /branccode/ ) ;
+       $linefilter = @$filters[3] if ($line =~ /sort1/ ) ;
+       $linefilter = @$filters[4] if ($line =~ /sort2/ ) ;
 # 
        my $colfilter = "";
        $colfilter = @$filters[0] if ($column =~ /categorycode/);
        $colfilter = @$filters[1] if ($column =~ /zipcode/);
-       $colfilter = @$filters[2] if ($column =~ /sort1/);
-       $colfilter = @$filters[3] if ($column =~ /sort2/);
+       $colfilter = @$filters[2] if ($column =~ /branchcode/);
+       $colfilter = @$filters[3] if ($column =~ /sort1/);
+       $colfilter = @$filters[4] if ($column =~ /sort2/);
 
        my @loopfilter;
        for (my $i=0;$i<=3;$i++) {
@@ -223,8 +240,9 @@ sub calculate {
                        $cell{filter} .= @$filters[$i];
                        $cell{crit} .="Cat Code " if ($i==0);
                        $cell{crit} .="Zip Code" if ($i==1);
-                       $cell{crit} .="Sort1" if ($i==2);
-                       $cell{crit} .="Sort2" if ($i==3);
+                       $cell{crit} .="Branchcode" if ($i==2);
+                       $cell{crit} .="Sort1" if ($i==3);
+                       $cell{crit} .="Sort2" if ($i==4);
                        push @loopfilter, \%cell;
                }
        }
@@ -278,10 +296,10 @@ sub calculate {
        $strsth2 .= "select distinctrow $colfield from borrowers where $column is not null";
        if ( $colfilter ) {
                $strsth2 .= " and $colfield LIKE ? ";
-       } 
+       }
        $strsth2 .= " and $status='1' " if ($status);
        $strsth2 .= " order by $colfield";
-       warn "". $strsth2;
+#      warn "". $strsth2;
        my $sth2 = $dbh->prepare( $strsth2 );
        if ($colfilter) {
                $sth2->execute($colfilter);
@@ -385,4 +403,3 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
index fddcf6d..1d116c3 100755 (executable)
@@ -23,13 +23,13 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use HTML::Template;
-use C4::Search;
+use C4::Branch; # GetBranches
 use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 use Date::Manip;
+use C4::Members;
 
 =head1 NAME
 
@@ -58,10 +58,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => { reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($limit, $column, \@filters);
@@ -74,6 +78,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -133,10 +138,50 @@ if ($do_it) {
                                -values   => \@dels,
                                -size     => 1,
                                -multiple => 0 );
+       #branch
+       my $branches = GetBranches;
+       my @branchloop;
+       foreach my $thisbranch (keys %$branches) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisbranch,
+#                                                                      selected => $selected,
+                                                                       branchname => $branches->{$thisbranch}->{'branchname'},
+                                                       );
+                       push @branchloop, \%row;
+       }
+
+       #doctype
+       my $itemtypes = GetItemTypes;
+       my @itemtypeloop;
+       foreach my $thisitemtype (keys %$itemtypes) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisitemtype,
+#                                                                      selected => $selected,
+                                                                       description => $itemtypes->{$thisitemtype}->{'description'},
+                                                       );
+                       push @itemtypeloop, \%row;
+       }
+       
+       #borcat
+       my ($codes,$labels) = GetborCatFromCatType(undef,undef);
+       my @borcatloop;
+       foreach my $thisborcat (sort keys %$labels) {
+ #                     my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisborcat,
+ #                                                                     selected => $selected,
+                                                                       description => $labels->{$thisborcat},
+                                                       );
+                       push @borcatloop, \%row;
+       }
        
+       #Day
+       #Month
        $template->param(
                                        CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
+                                       CGIsepChoice => $CGIsepChoice,
+                                       branchloop =>\@branchloop,
+                                       itemtypeloop =>\@itemtypeloop,
+                                       borcatloop =>\@borcatloop,
                                        );
 output_html_with_http_headers $input, $cookie, $template->output;
 }
@@ -251,10 +296,7 @@ sub calculate {
        
                while (my ($celvalue) = $sth2->fetchrow) {
                        my %cell;
-       #               my %ft;
-       #               warn "coltitle :".$celvalue;
-                       $cell{coltitle} = $celvalue;
-       #               $ft{totalcol} = 0;
+                       $cell{coltitle} = ($celvalue?$celvalue:"NULL");
                        push @loopcol, \%cell;
                }
        #       warn "fin des titres colonnes";
@@ -307,31 +349,29 @@ sub calculate {
        
        $strcalc .= " group by biblio.biblionumber";
        $strcalc .= ", $colfield" if ($column);
-       $strcalc .= " order by ";
-       $strcalc .= "$colfield, " if ($colfield);
-       $strcalc .= "RANK DESC ";
-       my $max;
-       if (@loopcol) {
-               $max = $line*@loopcol;
-       } else { $max=$line;}
-       $strcalc .= " LIMIT 0,$max";
+       $strcalc .= " order by RANK DESC";
+       $strcalc .= ", $colfield " if ($colfield);
+#      my $max;
+#      if (@loopcol) {
+#              $max = $line*@loopcol;
+#      } else { $max=$line;}
+#      $strcalc .= " LIMIT 0,$max";
        warn "SQL :". $strcalc;
        
        my $dbcalc = $dbh->prepare($strcalc);
        $dbcalc->execute;
 #      warn "filling table";
        my $previous_col;
-       my $i=1;
+       my %indice;
        while (my  @data = $dbcalc->fetchrow) {
                my ($row, $rank, $id, $col )=@data;
                $col = "zzEMPTY" if ($col eq undef);
-               $i=1 if (($previous_col) and not($col eq $previous_col));
-               $table[$i]->{$col}->{'name'}=$row;
-               $table[$i]->{$col}->{'count'}=$rank;
-               $table[$i]->{$col}->{'link'}=$id;
+               $indice{$col}=1 if (not($indice{$col}));
+               $table[$indice{$col}]->{$col}->{'name'}=$row;
+               $table[$indice{$col}]->{$col}->{'count'}=$rank;
+               $table[$indice{$col}]->{$col}->{'link'}=$id;
 #              warn " ".$i." ".$col. " ".$row;
-               $i++;
-               $previous_col=$col;
+               $indice{$col}++;
        }
        
        push @loopcol,{coltitle => "Global"} if not($column);
@@ -385,4 +425,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index 3a7c242..b776783 100755 (executable)
@@ -23,8 +23,7 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use HTML::Template;
-use C4::Search;
+use C4::Branch; # GetBranches
 use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
@@ -58,10 +57,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($limit, $column, \@filters);
@@ -73,6 +76,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -132,10 +136,35 @@ if ($do_it) {
                                -values   => \@dels,
                                -size     => 1,
                                -multiple => 0 );
+       #doctype
+       my $itemtypes = GetItemTypes;
+       my @itemtypeloop;
+       foreach my $thisitemtype (keys %$itemtypes) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisitemtype,
+#                                                                      selected => $selected,
+                                                                       description => $itemtypes->{$thisitemtype}->{'description'},
+                                                       );
+                       push @itemtypeloop, \%row;
+       }
+               
+       #branch
+       my $branches = GetBranches;
+       my @branchloop;
+       foreach my $thisbranch (keys %$branches) {
+#                      my $selected = 1 if $thisbranch eq $branch;
+                       my %row =(value => $thisbranch,
+#                                                                      selected => $selected,
+                                                                       branchname => $branches->{$thisbranch}->{'branchname'},
+                                                       );
+                       push @branchloop, \%row;
+       }
        
        $template->param(
                                        CGIextChoice => $CGIextChoice,
-                                       CGIsepChoice => $CGIsepChoice
+                                       CGIsepChoice => $CGIsepChoice,
+                                       itemtypeloop =>\@itemtypeloop,
+                                       branchloop =>\@branchloop,
                                        );
 output_html_with_http_headers $input, $cookie, $template->output;
 }
@@ -231,9 +260,9 @@ sub calculate {
        my $strcalc ;
        
 # Processing average loanperiods
-       $strcalc .= "SELECT CONCAT( items.itemnumber, \" \",biblioitems.biblioitemnumber)";
+       $strcalc .= "SELECT items.barcode, biblio.title, biblio.biblionumber, biblio.author";
        $strcalc .= " , $colfield " if ($colfield);
-       $strcalc .= " FROM (items LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber)  LEFT JOIN issues ON  issues.itemnumber=items.itemnumber WHERE issues.itemnumber is null";
+       $strcalc .= " FROM (items LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber  LEFT JOIN biblio ON biblio.biblionumber=items.biblionumber) LEFT JOIN issues ON  issues.itemnumber=items.itemnumber WHERE issues.itemnumber is null";
 #      @$filters[0]=~ s/\*/%/g if (@$filters[0]);
 #      $strcalc .= " AND issues.timestamp <= '" . @$filters[0] ."'" if ( @$filters[0] );
 #      @$filters[1]=~ s/\*/%/g if (@$filters[1]);
@@ -263,10 +292,13 @@ sub calculate {
        my $previous_col;
        my $i=1;
        while (my  @data = $dbcalc->fetchrow) {
-               my ($row, $col )=@data;
+               my ($barcode,$title,$bibnum,$author, $col )=@data;
                $col = "zzEMPTY" if ($col eq undef);
                $i=1 if (($previous_col) and not($col eq $previous_col));
-               $table[$i]->{$col}=$row;
+               $table[$i]->{$col}->{'barcode'}=$barcode;
+               $table[$i]->{$col}->{'title'}=$title;
+               $table[$i]->{$col}->{'bibnum'}=$bibnum;
+               $table[$i]->{$col}->{'author'}=$author;
 #              warn " ".$i." ".$col. " ".$row;
                $i++;
                $previous_col=$col;
@@ -281,13 +313,19 @@ sub calculate {
                # and the number matches the number of columns
                my $colcount=0;
                foreach my $col ( @loopcol ) {
-                       my $value;
+                       my ($barcode, $author, $title, $bibnum);
                        if (@loopcol){
-                               $value =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}};
+                               $barcode =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'barcode'};
+                               $title =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'title'};
+                               $author =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'author'};
+                               $bibnum =$table[$i]->{(($col->{coltitle} eq "NULL") or ($col->{coltitle} eq "Global"))?"zzEMPTY":$col->{coltitle}}->{'bibnum'};
                        } else {
-                               $value =$table[$i]->{"zzEMPTY"};
+                               $barcode =$table[$i]->{"zzEMPTY"}->{'barcode'};
+                               $title =$table[$i]->{"zzEMPTY"}->{'title'};
+                               $author =$table[$i]->{"zzEMPTY"}->{'author'};
+                               $bibnum =$table[$i]->{"zzEMPTY"}->{'bibnum'};
                        }
-                       push @loopcell, {value => $value} ;
+                       push @loopcell, {author=> $author, title=>$title,bibnum=>$bibnum,barcode=>$barcode} ;
                }
                push @looprow,{ 'rowtitle' => $i ,
                                                'loopcell' => \@loopcell,
@@ -312,4 +350,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index 8a036b3..b1e6d5f 100755 (executable)
@@ -1,5 +1,5 @@
 #!/usr/bin/perl
-## Will not work. Requires a complete re-write for ZEBRA
+
 # $Id$
 
 # Copyright 2000-2002 Katipo Communications
@@ -23,7 +23,7 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+use C4::Branch; # GetBranches
 use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
@@ -31,7 +31,7 @@ use C4::Circulation::Circ2;
 
 =head1 NAME
 
-plugin that shows a stats on catalogue
+plugin that shows a stats on borrowers
 
 =head1 DESCRIPTION
 
@@ -59,7 +59,7 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
 $template->param(do_it => $do_it);
@@ -71,6 +71,7 @@ if ($do_it) {
                exit(1);
        } else {
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                                                         -attachment=>"$basename.csv",
                                                         -name=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -105,66 +106,99 @@ if ($do_it) {
        my %labels;
        my $count=0;
        my $req;
-###Use mfield of koha_attr instead of dewey
-my $sth = $dbh->prepare("select authorised_value from authorised_values where category='mfield' order by lib");
-       $sth->execute;
-       my @authorised_values;
-       #push @authorised_values,"";
-       while ((my $category) = $sth->fetchrow_array) {
-               push @authorised_values, $category;
+       $req = $dbh->prepare("select count(dewey) from biblioitems ");
+       $req->execute;
+       my $hasdewey;
+       my @select;
+#      push @select,"";
+       while (my ($value) =$req->fetchrow) {
+               $hasdewey =1 if (($value>2) and (! $hasdewey));
+               $count++ if (($value>2) and (! $hasdewey));
+#              push @select, $value;
        }
-my $hasdewey;
-       my $CGIdewey=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@authorised_values,
-                               -size     => 1,
-                               -multiple => 0 );
+#      my $CGIdewey=CGI::scrolling_list( -name     => 'Filter',
+#                              -id => 'Filter',
+#                              -values   => \@select,
+#                              -size     => 1,
+#                              -multiple => 0 );
        
-
-       my $haslccn=1;
-       my $hlghtlccn=1;
-       my @select;
-       for my $value ("A".."Z") {
-               push @select, $value;
+       $req = $dbh->prepare( "select count(lccn) from biblioitems ");
+       $req->execute;
+#      undef @select;
+#      push @select,"";
+       my $haslccn;
+       my $hlghtlccn;
+       while (my ($value) =$req->fetchrow) {
+               $hlghtlccn = !($hasdewey);
+               $haslccn =1 if (($value>2) and (! $haslccn));
+               $count++ if (($value) and (! $haslccn));
+#              push @select, $value;
        }
-       my $CGIlccn=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'Filter',
-                               -values   => \@select,
-                               -size     => 1,
-                               -multiple => 0 );
+#      my $CGIlccn=CGI::scrolling_list( -name     => 'Filter',
+#                              -id => 'Filter',
+#                              -values   => \@select,
+#                              -size     => 1,
+#                              -multiple => 0 );
        
+       $req = $dbh->prepare("select count(itemcallnumber) from items");
+       $req->execute;
+#      undef @select;
+#      push @select,"";
        my $hascote;
        my $hlghtcote;
+       while (my ($value) =$req->fetchrow) {
+               $hascote =1 if (($value>2) and (! $hascote));
+               $count++ if (($value) and (! $hascote));
+               $hlghtcote = (($hasdewey) and ($haslccn)) or (!($hasdewey) and !($haslccn));
+#              push @select, $value;
+       }
+#      my $CGIcote=CGI::scrolling_list( -name     => 'Filter',
+#                              -id => 'Filter',
+#                              -values   => \@select,
+#                              -size     => 1,
+#                              -multiple => 0 );
        $count++;
        my $hglghtDT =$count % 2;
+#      warn "highlightDT ".$hglghtDT;
        $count++;
        my $hglghtPub =$count % 2;
+#      warn "highlightPub ".$hglghtPub;
        $count++;
        my $hglghtPY =$count % 2;
+#      warn "highlightPY ".$hglghtPY;
        $count++;
        my $hglghtHB =$count % 2;
+#      warn "highlightHB ".$hglghtHB;
        $count++;
        my $hglghtLOC =$count % 2;
-       my $hglghtSTACK =$count % 2;
+#      warn "highlightLOC ".$hglghtLOC;
        
-       my $itemtypes = GetItemTypes;
+       
+       $req = $dbh->prepare("select distinctrow itemtype from biblioitems order by itemtype");
+       $req->execute;
        undef @select;
        push @select,"";
-       my %select_item;
-       $select_item{""} = "";
-foreach my $thisitemtype (sort keys %$itemtypes) {
-       push @select,$thisitemtype;
-       $select_item{$thisitemtype}=$itemtypes->{$thisitemtype}->{'description'};
-
-}
-
+       while (my ($value) =$req->fetchrow) {
+               push @select, $value;
+       }
        my $CGIitemtype=CGI::scrolling_list( -name     => 'Filter',
                                -id => 'itemtype',
                                -values   => \@select,
-                               -labels=>\%select_item,
                                -size     => 1,
                                -multiple => 0 );
        
+#      $req = $dbh->prepare("select distinctrow left(publishercode,75) from biblioitems order by publishercode");
+#      $req->execute;
+#      undef @select;
+#      push @select,"";
+#      while (my ($value) =$req->fetchrow) {
+#              push @select, $value;
+#      }
+#      my $CGIpublisher=CGI::scrolling_list( -name     => 'Filter',
+#                              -id => 'Filter',
+#                              -values   => \@select,
+#                              -size     => 1,
+#                              -multiple => 0 );
 
        undef @select;
        push @select,"";
@@ -181,28 +215,14 @@ foreach my $thisitemtype (sort keys %$itemtypes) {
                                -labels   => \%select_branches,
                                -size     => 1,
                                -multiple => 0 );
-
-       my $CGIholdingbranch=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'holdingbranch',
-                               -values   => \@select,
-                               -labels   => \%select_branches,
-                               -size     => 1,
-                               -multiple => 0 );
-       $req = $dbh->prepare("select authorised_value,lib from authorised_values where category='sections'");
+       
+       $req = $dbh->prepare("select distinctrow holdingbranch from items order by holdingbranch");
        $req->execute;
        undef @select;
        push @select,"";
-       my %desc;
-       $desc{""}="";
-       while (my ($value,$desc) =$req->fetchrow) {
-               push @select, $value;
-               $desc{$value}=$desc;
-       }
-
-       my $CGISTACK=CGI::scrolling_list( -name     => 'Filter',
-                               -id => 'shelf',
+       my $CGIlocation=CGI::scrolling_list( -name     => 'Filter',
+                               -id => 'holdingbranch',
                                -values   => \@select,
-                               -labels =>\%desc,
                                -size     => 1,
                                -multiple => 0 );
        
@@ -227,12 +247,12 @@ foreach my $thisitemtype (sort keys %$itemtypes) {
                                -multiple => 0 );
        
        $template->param(hasdewey=>$hasdewey,
-                                       CGIFromDeweyClass => $CGIdewey,
-                                       CGIToDeweyClass => $CGIdewey,
+#                                      CGIFromDeweyClass => $CGIdewey,
+#                                      CGIToDeweyClass => $CGIdewey,
                                        haslccn=> $haslccn,
                                        hlghtlccn => $hlghtlccn,
-                                       CGIFromLoCClass => $CGIlccn,
-                                       CGIToLoCClass => $CGIlccn,
+#                                      CGIFromLoCClass => $CGIlccn,
+#                                      CGIToLoCClass => $CGIlccn,
                                        hascote=> $hascote,
                                        hlghtcote => $hlghtcote,
                                        hglghtDT => $hglghtDT,
@@ -240,11 +260,14 @@ foreach my $thisitemtype (sort keys %$itemtypes) {
                                        hglghtPY => $hglghtPY,
                                        hglghtHB => $hglghtHB,
                                        hglghtLOC => $hglghtLOC,
-                                       hglghtSTACK => $hglghtSTACK,
+#                                      CGIFromCoteClass => $CGIcote,
+#                                      CGIToCoteClass => $CGIcote,
                                        CGIItemType => $CGIitemtype,
+#                                      CGIFromPublicationYear => $CGIpublicationyear,
+#                                      CGIToPublicationYear => $CGIpublicationyear,
+#                                      CGIPublisher => $CGIpublisher,
                                        CGIBranch => $CGIbranch,
-                                       CGILocation => $CGIbranch,
-                                       CGISTACK => $CGISTACK,
+                                       CGILocation => $CGIlocation,
                                        CGIextChoice => $CGIextChoice,
                                        CGIsepChoice => $CGIsepChoice
                                        );
@@ -279,17 +302,16 @@ sub calculate {
                        $cell{filter} .= @$filters[$i];
                        $cell{crit} .="Dewey Classification From" if ($i==0);
                        $cell{crit} .="Dewey Classification To" if ($i==1);
-                       $cell{crit} .="Classification From" if ($i==2);
-                       $cell{crit} .="Classification To" if ($i==3);
-                       $cell{crit} .="Call Number From" if ($i==4);
-                       $cell{crit} .="Call Number To" if ($i==5);
+                       $cell{crit} .="Lccn Classification From" if ($i==2);
+                       $cell{crit} .="Lccn Classification To" if ($i==3);
+                       $cell{crit} .="Cote Classification From" if ($i==4);
+                       $cell{crit} .="Cote Classification To" if ($i==5);
                        $cell{crit} .="Document type" if ($i==6);
                        $cell{crit} .="Publisher" if ($i==7);
                        $cell{crit} .="Publication year From" if ($i==8);
                        $cell{crit} .="Publication year To" if ($i==9);
                        $cell{crit} .="Branch :" if ($i==10);
                        $cell{crit} .="Location:" if ($i==11);
-                       $cell{crit} .="Shelving:" if ($i==12);
                        push @loopfilter, \%cell;
                }
        }
@@ -302,47 +324,46 @@ sub calculate {
        
        $linefilter[0] = @$filters[0] if ($line =~ /dewey/ )  ;
        $linefilter[1] = @$filters[1] if ($line =~ /dewey/ )  ;
-       $linefilter[0] = @$filters[2] if ($line =~ /classification/ )  ;
-       $linefilter[1] = @$filters[3] if ($line =~ /classification/ )  ;
-       $linefilter[0] = @$filters[4] if ($line =~ /itemcallnumber/ )  ;
-       $linefilter[1] = @$filters[5] if ($line =~ /itemcallnumber/ )  ;
+       $linefilter[0] = @$filters[2] if ($line =~ /lccn/ )  ;
+       $linefilter[1] = @$filters[3] if ($line =~ /lccn/ )  ;
+       $linefilter[0] = @$filters[4] if ($line =~ /items.itemcallnumber/ )  ;
+       $linefilter[1] = @$filters[5] if ($line =~ /items.itemcallnumber/ )  ;
        $linefilter[0] = @$filters[6] if ($line =~ /itemtype/ )  ;
        $linefilter[0] = @$filters[7] if ($line =~ /publishercode/ ) ;
        $linefilter[0] = @$filters[8] if ($line =~ /publicationyear/ ) ;
        $linefilter[1] = @$filters[9] if ($line =~ /publicationyear/ ) ;
-       $linefilter[0] = @$filters[10] if ($line =~ /homebranch/ ) ;
-       $linefilter[0] = @$filters[11] if ($line =~ /holdingbranch/ ) ;
-       $linefilter[0] = @$filters[12] if ($line =~ /shelf/ ) ;
+       @linefilter[0] = @$filters[10] if ($line =~ /items.homebranch/ ) ;
+       @linefilter[0] = @$filters[11] if ($line =~ /items.holdingbranch/ ) ;
 # 
        my @colfilter ;
        $colfilter[0] = @$filters[0] if ($column =~ /dewey/ )  ;
        $colfilter[1] = @$filters[1] if ($column =~ /dewey/ )  ;
-       $colfilter[0] = @$filters[2] if ($column =~ /classification/ )  ;
-       $colfilter[1] = @$filters[3] if ($column =~ /classification/ )  ;
+       $colfilter[0] = @$filters[2] if ($column =~ /lccn/ )  ;
+       $colfilter[1] = @$filters[3] if ($column =~ /lccn/ )  ;
        $colfilter[0] = @$filters[4] if ($column =~ /itemcallnumber/ )  ;
        $colfilter[1] = @$filters[5] if ($column =~ /itemcallnumber/ )  ;
        $colfilter[0] = @$filters[6] if ($column =~ /itemtype/ )  ;
        $colfilter[0] = @$filters[7] if ($column =~ /publishercode/ ) ;
        $colfilter[0] = @$filters[8] if ($column =~ /publicationyear/ ) ;
        $colfilter[1] = @$filters[9] if ($column =~ /publicationyear/ ) ;
-       $colfilter[0] = @$filters[10] if ($column =~ /homebranch/ ) ;
-       $colfilter[0] = @$filters[11] if ($column =~ /holdingbranch/ ) ;
-       $colfilter[0] = @$filters[12] if ($column =~ /shelf/ ) ;
+       @colfilter[0] = @$filters[10] if ($column =~ /items.homebranch/ ) ;
+       @colfilter[0] = @$filters[11] if ($column =~ /items.holdingbranch/ ) ;
+
 # 1st, loop rows.
        my $linefield;
        if (($line =~/dewey/)  and ($deweydigits)) {
                $linefield .="left($line,$deweydigits)";
-       } elsif (($line=~/classification/) and ($lccndigits)) {
+       } elsif (($line=~/lccn/) and ($lccndigits)) {
                $linefield .="left($line,$lccndigits)";
-       } elsif (($line=~/itemcallnumber/) and ($cotedigits)) {
+       } elsif (($line=~/items.itemcallnumber/) and ($cotedigits)) {
                $linefield .="left($line,$cotedigits)";
        }else {
                $linefield .= $line;
        }
        
-warn $linefield,$colfilter[0],$linefilter[0],$line;    
+       
        my $strsth;
-       $strsth .= "select distinctrow $linefield from biblio left join items on (items.biblionumber = biblio.biblionumber) where $line is not null ";
+       $strsth .= "select distinctrow $linefield from biblioitems left join items on (items.biblioitemnumber = biblioitems.biblioitemnumber) where $line is not null ";
        if ( @linefilter ) {
                if ($linefilter[1]){
                        $strsth .= " and $line >= ? " ;
@@ -378,7 +399,7 @@ warn $linefield,$colfilter[0],$linefilter[0],$line;
        my $colfield;
        if (($column =~/dewey/)  and ($deweydigits)) {
                $colfield .="left($column,$deweydigits)";
-       }elsif (($column=~/classification/) and ($lccndigits)) {
+       }elsif (($column=~/lccn/) and ($lccndigits)) {
                $colfield .="left($column,$lccndigits)";
        }elsif (($column=~/itemcallnumber/) and ($cotedigits)) {
                $colfield .="left($column,$cotedigits)";
@@ -387,7 +408,7 @@ warn $linefield,$colfilter[0],$linefilter[0],$line;
        }
        
        my $strsth2;
-       $strsth2 .= "select distinctrow $colfield from biblio left join items on (items.biblionumber = biblio.biblionumber) where $column is not null ";
+       $strsth2 .= "select distinctrow $colfield from biblioitems left join items on (items.biblioitemnumber = biblioitems.biblioitemnumber) where $column is not null ";
        if (( @colfilter ) and ($colfilter[1])) {
                $strsth2 .= " and $column> ? and $column< ?";
        }elsif ($colfilter[0]){
@@ -431,83 +452,45 @@ warn $linefield,$colfilter[0],$linefilter[0],$line;
                }
                $table{$row->{rowtitle}}->{totalrow}=0;
        }
-my @kohafield;
-my @values;
-my @and_or;
-my @relations;
-# preparing calculation in zebra
+
+# preparing calculation
        my $strcalc .= "SELECT $linefield, $colfield, count( * ) FROM biblioitems LEFT JOIN  items ON (items.biblioitemnumber = biblioitems.biblioitemnumber) WHERE 1";
        if (@$filters[0]){
                @$filters[0]=~ s/\*/%/g;
                $strcalc .= " AND dewey >" . @$filters[0] ."";
-               push @and_or, "\@and";
-               push @relations "\@attr 2=5";
-               push @kohafield, "dewey";
-               push @values,  @$filters[0] ;
-
        }
        if (@$filters[1]){
                @$filters[1]=~ s/\*/%/g ;
                $strcalc .= " AND dewey <" . @$filters[1] ."";
-               push @and_or, "\@and";
-               push @relations "\@attr 2=1";
-               push @kohafield, "dewey";
-               push @values,  @$filters[1] ;
-
                
        }
        if (@$filters[2]){
                @$filters[2]=~ s/\*/%/g ;
-               $strcalc .= " AND classification >=" .$dbh->quote(@$filters[2]) ."" ;
-               push @and_or, "\@and";
-               push @relations "\@attr 2=4";
-               push @kohafield, "classification";
-               push @values,  @$filters[2];
-
+               $strcalc .= " AND lccn >" . @$filters[2] ."" ;
        }
        if (@$filters[3]){
                @$filters[3]=~ s/\*/%/g;
-               $strcalc .= " AND classification <=" . $dbh->quote(@$filters[3]) ."" ;
-               push @and_or, "\@and";
-               push @relations "\@attr 2=2";
-               push @kohafield, "classification";
-               push @values,  @$filters[3] ;
+               $strcalc .= " AND lccn <" . @$filters[3] ."" ;
        }
        if (@$filters[4]){
                @$filters[4]=~ s/\*/%/g ;
                $strcalc .= " AND items.itemcallnumber >=" . $dbh->quote(@$filters[4]) ."" ;
-               push @and_or, "\@and";
-               push @relations "\@attr 2=4";
-               push @kohafield, "itemcallnumber";
-               push @values,  @$filters[4] ;
        }
        
        if (@$filters[5]){
                @$filters[5]=~ s/\*/%/g;
                $strcalc .= " AND items.itemcallnumber <=" . $dbh->quote(@$filters[5]) ."" ;
-               push @and_or, "\@and";
-               push @relations "\@attr 2=2";
-               push @kohafield, "itemcallnumber";
-               push @values,  @$filters[5] ;
        }
        
        if (@$filters[6]){
                @$filters[6]=~ s/\*/%/g;
                $strcalc .= " AND biblioitems.itemtype like '" . @$filters[6] ."'";
-               push @and_or, "\@and";
-               push @relations "\@attr 2=3";
-               push @kohafield, "itemtype";
-               push @values,  @$filters[6] ;
        }
        
        if (@$filters[7]){
                @$filters[7]=~ s/\*/%/g;
                @$filters[7].="%" unless @$filters[7]=~/%/;
                $strcalc .= " AND biblioitems.publishercode like \"" . @$filters[7] ."\"";
-               push @and_or, "\@and";
-               push @relations "\@attr 2=3";
-               push @kohafield, "publishercode";
-               push @values,  @$filters[7]; 
        }
        if (@$filters[8]){
                @$filters[8]=~ s/\*/%/g;
@@ -525,14 +508,11 @@ my @relations;
                @$filters[11]=~ s/\*/%/g;
                $strcalc .= " AND items.holdingbranch like '" . @$filters[11] ."'" if ( @$filters[11] );
        }
-       if (@$filters[12]){
-               @$filters[12]=~ s/\*/%/g;
-               $strcalc .= " AND items.stack like '" . @$filters[12] ."'" if ( @$filters[12] );
-       }
+       
        $strcalc .= " group by $linefield, $colfield order by $linefield,$colfield";
        warn "". $strcalc;
        my $dbcalc = $dbh->prepare($strcalc);
-#      $dbcalc->execute;
+       $dbcalc->execute;
 #      warn "filling table";
        
        my $emptycol; 
@@ -547,6 +527,11 @@ my @relations;
                $grantotal += $value;
        }
 
+#      my %cell = {rowtitle => 'zzROWEMPTY'};
+#      push @loopline,\%cell;
+#      undef %cell;
+#      my %cell;
+#      %cell = {coltitle => "zzEMPTY"};
        push @loopcol,{coltitle => "NULL"} if ($emptycol);
        
        foreach my $row ( sort keys %table ) {
@@ -591,4 +576,4 @@ my @relations;
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index d6c3be5..1ba0af1 100755 (executable)
@@ -24,7 +24,8 @@ use C4::Context;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
-use C4::Biblio;
+use C4::Date;
+
 
 # Fixed variables
 my $linecolor1='#ffffcc';
@@ -38,60 +39,90 @@ my $pagepagesize=20;
 # Main loop....
 my $input = new CGI;
 my $minlocation=$input->param('minlocation');
-#my $maxlocation=$input->param('maxlocation');
-#$maxlocation=$minlocation.'Z' unless $maxlocation;
+my $maxlocation=$input->param('maxlocation');
+$maxlocation=$minlocation.'Z' unless $maxlocation;
 my $datelastseen = $input->param('datelastseen');
 my $offset = $input->param('offset');
 my $markseen = $input->param('markseen');
 $offset=0 unless $offset;
 my $pagesize = $input->param('pagesize');
 $pagesize=20 unless $pagesize;
+my $uploadbarcodes = $input->param('uploadbarcodes');
+# warn "uploadbarcodes : ".$uploadbarcodes;
 
 my ($template, $borrowernumber, $cookie)
     = get_template_and_user({template_name => "reports/inventory.tmpl",
                             query => $input,
                             type => "intranet",
                             authnotrequired => 0,
-                            flagsrequired => {editcatalogue => 1},
+                            flagsrequired => {reports => 1},
                             debug => 1,
                             });
 $template->param(minlocation => $minlocation,
-                               
+                               maxlocation => $maxlocation,
                                offset => $offset,
                                pagesize => $pagesize,
                                datelastseen => $datelastseen,
+                               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
                                );
-if ($markseen) {
-       foreach my $field ($input->param) {
-               if ($field =~ /SEEN-(.*)/) {
-                       &itemseen($1);
-                       &returnbook($1,"MAIN");
+if ($uploadbarcodes && length($uploadbarcodes)>0){
+       my $dbh=C4::Context->dbh;
+       my $date=format_date($input->param('setdate'));
+       $date = format_date("today") unless $date;
+#      warn "$date";
+       my $strsth="update items set (datelastseen = $date) where items.barcode =?";
+       my $qupdate = $dbh->prepare($strsth);
+       my $strsth="select * from issues, items where items.itemnumber=issues.itemnumber and items.barcode =? and issues.returndate is null";
+       my $qonloan = $dbh->prepare($strsth);
+       my $strsth="select * from items where items.barcode =? and issues.wthdrawn=1";
+       my $qwthdrawn = $dbh->prepare($strsth);
+       my @errorloop;
+       my $count=0;
+       while (my $barcode=<$uploadbarcodes>){
+               chomp $barcode;
+#              warn "$barcode";
+               if ($qwthdrawn->execute($barcode) &&$qwthdrawn->rows){
+                       push @errorloop, {'barcode'=>$barcode,'ERR_WTHDRAWN'=>1};
+               }else{
+                       $qupdate->execute($barcode);
+                       $count += $qupdate->rows;
+#                      warn "$count";
+                       if ($count){
+                               $qonloan->execute($barcode);
+                               if ($qonloan->rows){
+                                       my $data = $qonloan->fetchrow_hashref;
+                                       my ($doreturn, $messages, $iteminformation, $borrower) =returnbook($barcode, $data->{homebranch});
+                                       if ($doreturn){push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_RET'=>1}}
+                                       else {push @errorloop, {'barcode'=>$barcode,'ERR_ONLOAN_NOT_RET'=>1}}
+                               }
+                       } else {
+                               push @errorloop, {'barcode'=>$barcode,'ERR_BARCODE'=>1};
+                       }
                }
        }
-}
-if ($minlocation) {
-       my @results = listitemsforinventory($minlocation,$datelastseen,$offset,$pagesize);
-## @results is now a hash of kohaxml
-## convert to normal koha hash for the templates
-my @res;
-my $i=0;
-foreach my $xml(@results) {
-
-       my @kohafields; ## just parse the fields required
-       push @kohafields,"title","author","biblionumber","itemnumber","barcode","itemcallnumber";
-       my $dbh=C4::Context->dbh;
-       my ($biblio,@itemrecords) = XMLmarc2koha($dbh,$xml,"",@kohafields);
-                foreach my $data(@itemrecords){
-               $data->{title}=$biblio->{title};
-               $data->{author}=$biblio->{author};
-               push @res,$data;
-       
+       $qupdate->finish;
+       $qonloan->finish;
+       $qwthdrawn->finish;
+       $template->param(date=>$date,Number=>$count);
+#      $template->param(errorfile=>$errorfile) if ($errorfile);
+       $template->param(errorloop=>\@errorloop) if (@errorloop);
+}else{
+       if ($markseen) {
+               foreach my $field ($input->param) {
+                       if ($field =~ /SEEN-(.*)/) {
+                               &itemseen($1);
+                       }
                }
-}
-       $template->param(loop =>\@res,
-                                       nextoffset => ($offset+$pagesize),
-                                       prevoffset => ($offset?$offset-$pagesize:0),
-                                       );
+       }
+       if ($minlocation) {
+               my $res = C4::Circulation::Circ2::listitemsforinventory($minlocation,$maxlocation,$datelastseen,$offset,$pagesize);
+               $template->param(loop =>$res,
+                                               nextoffset => ($offset+$pagesize),
+                                               prevoffset => ($offset?$offset-$pagesize:0),
+                                               );
+       }
 }
 output_html_with_http_headers $input, $cookie, $template->output;
 
index 8721230..6122e2f 100755 (executable)
@@ -23,13 +23,12 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use HTML::Template;
-use C4::Search;
+use C4::Branch; # GetBranches
 use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
-use Date::Manip;
+use Date::Calc qw(Delta_Days);
 
 =head1 NAME
 
@@ -61,10 +60,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($line, $column, $rodsp, $podsp, $calc, \@filters);
@@ -76,6 +79,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -157,7 +161,7 @@ if ($do_it) {
                $hassort1 =1 if ($value);
                push @select, $value;
        }
-       my $branches=getbranches();
+       my $branches=GetBranches();
        my @select_branch;
        my %select_branches;
        push @select_branch,"";
@@ -337,7 +341,7 @@ sub calculate {
                $linefield .="Year($line)";
                $lineorder .= $line;  
        } elsif (($line=~/timestamp/) or ($line=~/returndate/)){
-               $linefield .= "date_format('$line',\"%Y-%m-%d\")";
+               $linefield .= "date_format(\'$line\',\"%Y-%m-%d\")";
                $lineorder .= $line;  
        } else {
                $linefield .= $line;
@@ -351,9 +355,9 @@ sub calculate {
                if ($linefilter[1] and ($linefilter[0])){
                        $strsth .= " and $line between '$linefilter[0]' and '$linefilter[1]' " ;
                } elsif ($linefilter[1]) {
-                               $strsth .= " and $line < '$linefilter[1]' " ;
+                               $strsth .= " and $line < \'$linefilter[1]\' " ;
                } elsif ($linefilter[0]) {
-                       $strsth .= " and $line > '$linefilter[0]' " ;
+                       $strsth .= " and $line > \'$linefilter[0]\' " ;
                }
                if ($linefilter[2]){
                        $strsth .= " and dayname($line) = '$linefilter[2]' " ;
@@ -475,7 +479,7 @@ sub calculate {
        
 # Processing average loanperiods
        $strcalc .= "SELECT $linefield, $colfield, ";
-       $strcalc .= " DATE_SUB(date_due, INTERVAL CAST(issuingrules.issuelength AS SIGNED INTEGER) * (CAST(issues.renewals AS SIGNED INTEGER)+1) DAY) AS issuedate, returndate, COUNT(*), date_due, issues.renewals, issuelength FROM `issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) LEFT JOIN issuingrules ON (issuingrules.branchcode=issues.branchcode AND  issuingrules.itemtype=biblioitems.itemtype AND  issuingrules.categorycode=borrowers.categorycode) WHERE issues.itemnumber=items.itemnumber AND issues.borrowernumber=borrowers.borrowernumber and returndate is not null";
+       $strcalc .= " issuedate, returndate, COUNT(*), date_due, issues.renewals, issuelength FROM `issues`,borrowers,biblioitems LEFT JOIN items ON (biblioitems.biblioitemnumber=items.biblioitemnumber) LEFT JOIN issuingrules ON (issuingrules.branchcode=issues.branchcode AND  issuingrules.itemtype=biblioitems.itemtype AND  issuingrules.categorycode=borrowers.categorycode) WHERE issues.itemnumber=items.itemnumber AND issues.borrowernumber=borrowers.borrowernumber and returndate is not null";
 
        @$filters[0]=~ s/\*/%/g if (@$filters[0]);
        $strcalc .= " AND issues.timestamp > '" . @$filters[0] ."'" if ( @$filters[0] );
@@ -521,10 +525,10 @@ sub calculate {
                $col = "zzEMPTY" if ($col eq undef);
                $row = "zzEMPTY" if ($row eq undef);
 #              warn "506 row :".$row." column :".$col;
-               my @result =split /:/,DateCalc($returndate,$issuedate) ;
+               my $result =Delta_Days(split(/-/,$issuedate),split (/-/,$returndate)) ;
 #  DateCalc returns => 0:0:WK:DD:HH:MM:SS   the weeks, days, hours, minutes,
 #  and seconds between the two
-               $loanlength = $result[2]*7+$result[3];
+               $loanlength = $result;
 #              warn "512 Same row and col DateCalc returns :$loanlength with return ". $returndate ."issue ". $issuedate ."weight : ". $weight;
 #              warn "513 row :".$row." column :".$col;
                $table{$row}->{$col}+=$weight*$loanlength;
@@ -589,4 +593,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index 9b3d542..888a21d 100644 (file)
@@ -23,9 +23,11 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
+use HTML::Template;
 use C4::Search;
 use C4::Output;
 use C4::Koha;
+use C4::Branch; # GetBranches
 
 =head1 NAME
 
@@ -100,13 +102,13 @@ sub calculate {
        }
 # now, parse each category. Before filling the result array, fill it with 0 to have every itemtype column.
        my $strsth="SELECT itemtype, count( * )
-                               FROM issues, borrowers, biblio, items
+                               FROM issues, borrowers, biblioitems, items
                                WHERE issues.borrowernumber = borrowers.borrowernumber 
                                        AND items.itemnumber = issues.itemnumber 
-                                       AND biblio.biblionumber = items.biblionumber 
+                                       AND biblioitems.biblionumber = items.biblionumber 
                                        AND borrowers.categorycode = ?";
        $strsth.= " AND borrowers.branchcode = ".$dbh->quote($branch) if ($branch);
-       $strsth .= " GROUP BY biblio.itemtype";
+       $strsth .= " GROUP BY biblioitems.itemtype";
        my $sth = $dbh->prepare($strsth);
        my $sthcategories = $dbh->prepare("select categorycode,description from categories");
        $sthcategories->execute;
@@ -227,4 +229,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index d39b489..5d624cf 100755 (executable)
@@ -23,7 +23,8 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
-use C4::Search;
+use C4::Branch; # GetBranches
+use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
@@ -40,8 +41,6 @@ plugin that shows a stats on borrowers
 
 =cut
 
-
-
 my $input = new CGI;
 my $do_it=$input->param('do_it');
 my $fullreportname = "reports/issues_stats.tmpl";
@@ -63,10 +62,14 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
-$template->param(do_it => $do_it);
+$template->param(do_it => $do_it,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 if ($do_it) {
 # Displaying results
        my $results = calculate($line, $column, $podsp, $type, $daysel, $monthsel, $calc, \@filters);
@@ -78,6 +81,7 @@ if ($do_it) {
        } else {
 # Printing to a csv file
                print $input->header(-type => 'application/vnd.sun.xml.calc',
+                                     -encoding    => 'utf-8',
                        -attachment=>"$basename.csv",
                        -filename=>"$basename.csv" );
                my $cols = @$results[0]->{loopcol};
@@ -305,7 +309,7 @@ sub calculate {
        my $linefield;                               
        if (($line =~/datetime/) and ($dsp == 1)) {
                #Display by day
-               $linefield .="concat(weekday($line),' ',dayname($line))";  
+               $linefield .="dayname($line)";  
        } elsif (($line=~/datetime/) and ($dsp == 2)) {
                #Display by Month
                $linefield .="monthname($line)";  
@@ -318,7 +322,9 @@ sub calculate {
                $linefield .= $line;
        }  
        my $lineorder = $linefield;
-       $lineorder = "weekday($line)" if $lineorder =~ "^dayname";
+       $lineorder = "weekday($line)" if $linefield =~ /dayname/;
+       $lineorder = "month($line)" if $linefield =~ "^month";
+       $lineorder = $linefield if (not ($linefield =~ "^month") and not($linefield =~ /dayname/));
 
        my $strsth;
        $strsth .= "select distinctrow $linefield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $line is not null ";
@@ -363,7 +369,8 @@ sub calculate {
        }
 
 # 2nd, loop cols.
-       my $colfield;                               
+       my $colfield;
+       my $colorder;                               
        if (($column =~/datetime/) and ($dsp == 1)) {
                #Display by day
                $colfield .="dayname($column)";  
@@ -378,6 +385,9 @@ sub calculate {
        } else {
                $colfield .= $column;
        }  
+       $colorder = "weekday($line)" if $colfield =~ "^dayname";
+       $colorder = "month($line)" if $colfield =~ "^month";
+       $colorder = $colfield if (not ($colfield =~ "^month") and not($colfield =~ "^dayname"));
        
        my $strsth2;
        $strsth2 .= "select distinctrow $colfield from statistics, borrowers where (statistics.borrowernumber=borrowers.borrowernumber) and $column is not null ";
@@ -398,7 +408,7 @@ sub calculate {
                $strsth2 .= " and $column LIKE ? " ;
        }
        $strsth2 .=" group by $colfield";
-       $strsth2 .=" order by $colfield";
+       $strsth2 .=" order by $colorder";
 #      warn "". $strsth2;
        
        my $sth2 = $dbh->prepare( $strsth2 );
@@ -441,11 +451,17 @@ sub calculate {
 
        $strcalc .= "SELECT $linefield, $colfield, ";
        $strcalc .= "COUNT( * ) " if ($process ==1);
+       if ($process ==2){
+               $strcalc .= "(COUNT(DISTINCT borrowers.borrowernumber))" ;
+       }
        if ($process ==3){
+               $strcalc .= "(COUNT(DISTINCT issues.itemnumber))" ;
+       }
+       if ($process ==4){
                my $rqbookcount = $dbh->prepare("SELECT count(*) FROM items");
                $rqbookcount->execute;
                my ($bookcount) = $rqbookcount->fetchrow;
-               $strcalc .= "100*(COUNT(itemnumber))/ $bookcount " ;
+               $strcalc .= "100*(COUNT(DISTINCT issues.itemnumber))/ $bookcount " ;
        }
        $strcalc .= "FROM statistics,borrowers where (statistics.borrowernumber=borrowers.borrowernumber) ";
 
@@ -467,14 +483,14 @@ sub calculate {
        $strcalc .= " AND monthname(datetime) like '" . $monthsel ."'" if ( $monthsel );
        $strcalc .= " AND statistics.type like '" . $type ."'" if ( $type );
        
-       $strcalc .= " group by $linefield, $colfield order by $lineorder,$colfield";
+       $strcalc .= " group by $linefield, $colfield order by $lineorder,$colorder";
        warn "". $strcalc;
        my $dbcalc = $dbh->prepare($strcalc);
        $dbcalc->execute;
 #      warn "filling table";
        my $emptycol; 
        while (my ($row, $col, $value) = $dbcalc->fetchrow) {
-#              warn "filling table $row / $col / $value ";
+               warn "filling table $row / $col / $value ";
                $emptycol = 1 if ($col eq undef);
                $col = "zzEMPTY" if ($col eq undef);
                $row = "zzEMPTY" if ($row eq undef);
@@ -485,18 +501,18 @@ sub calculate {
        }
        push @loopcol,{coltitle => "NULL"} if ($emptycol);
 
-       foreach my $row ( sort keys %table ) {
+       foreach my $row (@loopline) {
                my @loopcell;
                #@loopcol ensures the order for columns is common with column titles
                # and the number matches the number of columns
                foreach my $col ( @loopcol ) {
-                       my $value =$table{$row}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
+                       my $value =$table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{($col->{coltitle} eq "NULL")?"zzEMPTY":$col->{coltitle}};
                        push @loopcell, {value => $value  } ;
                }
-               push @looprow,{ 'rowtitle' => ($row eq "zzEMPTY")?"NULL":$row,
+               push @looprow,{ 'rowtitle' => ($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle},
                                                        'loopcell' => \@loopcell,
                                                        'hilighted' => ($hilighted >0),
-                                                       'totalrow' => $table{$row}->{totalrow}
+                                                       'totalrow' => $table{($row->{rowtitle} eq "NULL")?"zzEMPTY":$row->{rowtitle}}->{totalrow}
                                                };
                $hilighted = -$hilighted;
        }
@@ -527,4 +543,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index 078df00..4443b86 100644 (file)
@@ -23,10 +23,11 @@ use strict;
 use C4::Auth;
 use CGI;
 use C4::Context;
+use HTML::Template;
 use C4::Search;
 use C4::Output;
 use C4::Koha;
-
+use C4::Branch; # GetBranches
 =head1
 
 =cut
@@ -60,14 +61,15 @@ sub calculate {
        my $dbh = C4::Context->dbh;
        my $sth;
        if ($branch) {
-               $sth = $dbh->prepare("select description, biblio.itemtype, count(*) as total from itemtypes, biblio, items 
-                                               where biblio.itemtype=itemtypes.itemtype 
-                                                       and items.biblionumber=biblio.biblionumber
+               $sth = $dbh->prepare("select description, biblioitems.itemtype, count(*) as total from itemtypes, biblioitems, items 
+                                               where biblioitems.itemtype=itemtypes.itemtype 
+                                                       and items.biblioitemnumber=biblioitems.biblioitemnumber
                                                        and items.holdingbranch=?
-                                               group by biblio.itemtype");
+                                               group by biblioitems.itemtype");
                $sth->execute($branch);
        } else {
-               $sth = $dbh->prepare("select description, biblio.itemtype, count(*) as total from itemtypes, biblio where biblio.itemtype=itemtypes.itemtype group by biblio.itemtype");
+               $sth = $dbh->prepare("select description, biblioitems.itemtype, count(*) as total from itemtypes, biblioitems,items where biblioitems.itemtype=itemtypes.itemtype 
+                                      and biblioitems.biblioitemnumber = items.biblioitemnumber group by biblioitems.itemtype");
                $sth->execute;
        }
        my ($description,$biblioitems,$total);
@@ -95,4 +97,4 @@ sub calculate {
        return \@mainloop;
 }
 
-1;
\ No newline at end of file
+1;
index bdd4a46..8628a1a 100755 (executable)
@@ -21,6 +21,7 @@ use strict;
 use CGI;
 use C4::Auth;
 use C4::Context;
+use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Circulation::Circ2;
 
@@ -35,11 +36,15 @@ my ($template, $borrowernumber, $cookie)
                                query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {editcatalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
 $template->param(do_it => $do_it,
-               report_name => $report_name);
+               report_name => $report_name,
+               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 my $cgidir = C4::Context->config('intranetdir')."/cgi-bin/reports/";
 unless (opendir(DIR, "$cgidir")) {
        $cgidir = C4::Context->intranetdir."/reports/";
index a220183..3d164fc 100644 (file)
@@ -1,12 +1,28 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+# 
+
 use strict;
 use CGI;
 use C4::Auth;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use HTML::Template;
+
 
 my $query = new CGI;
 my ($template, $loggedinuser, $cookie)
@@ -14,7 +30,11 @@ my ($template, $loggedinuser, $cookie)
                                query => $query,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
+                               flagsrequired => {reports => 1},
                                debug => 1,
                                });
+$template->param(intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+               IntranetNav => C4::Context->preference("IntranetNav"),
+               );
 output_html_with_http_headers $query, $cookie, $template->output;
index 347b6b4..692da8b 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
+# script now takes a branchcode arg
+# eg: http://koha.rangitikei.katipo.co.nz/cgi-bin/koha/reports/reservereport.pl?branch=BL
+
 use strict;
 use C4::Stats;
 use C4::Date;
 use CGI;
 use C4::Output;
+use C4::Branch; # GetBranches
 use C4::Auth;
 use C4::Interface::CGI::Output;
+use C4::Koha;
+
 
 my $input = new CGI;
 my $time  = $input->param('time');
+my $branch = $input->param('branch');
+my $sort = $input->param('sort');
+
+if (!$branch) {
+    $branch = "ALL";
+}
+
+my $branches=GetBranches();
 
 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
     {
@@ -37,12 +51,26 @@ my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
         query           => $input,
         type            => "intranet",
         authnotrequired => 0,
-        flagsrequired   => { editcatalogue => 1 },
+        flagsrequired   => { reports => 1 },
         debug           => 1,
     }
 );
 
-my ( $count, $data ) = unfilledreserves();
+# building up branches dropdown box
+
+my %branchall;
+my $branchcount=0;
+my @branchloop;
+
+foreach my $br (keys %$branches) {
+        $branchcount++;
+            my %branch1;
+            $branch1{name}=$branches->{$br}->{'branchname'};
+            $branch1{value}=$br;
+        push(@branchloop,\%branch1);
+    }  
+
+my ( $count, $data ) = unfilledreserves($branch);
 
 my @dataloop;
 my $toggle;
@@ -52,21 +80,71 @@ for ( my $i = 0 ; $i < $count ; $i++ ) {
        $line{'borrowernumber'} = $data->[$i]->{'borrowernumber'};
        $line{'surname'} = $data->[$i]->{'surname'};
        $line{'firstname'} = $data->[$i]->{'firstname'};
-    $line{'reservedate'}    = format_date($data->[$i]->{'reservedate'});
+        $line{'sortdate'}       = $data->[$i]->{'reservedate'};
+        $line{'reservedate'}    = format_date($data->[$i]->{'reservedate'});
        $line{'biblionumber'} = $data->[$i]->{'biblionumber'};
        $line{'title'} = $data->[$i]->{'title'};
        $line{'classification'} = $data->[$i]->{'classification'};
        $line{'dewey'} = $data->[$i]->{'dewey'};
-    $line{'status'} = $data->[$i]->{'found'};
+        $line{'status'} = $data->[$i]->{'found'};
+        $line{'branchcode'} = $data->[$i]->{'branchcode'};
        $line{'toggle'} = $toggle;
-
+     if ( $line{'status'} ne 'W' ) {
+        
+        # its not waiting, we need to find if its on issue, or on the shelf
+        # FIXME still need to shift the text to the template so its translateable
+        if ( $data->[$i]) {
+            # find if its on issue
+            my @items = &GetItemsInfo($line{'biblionumber'}, 'intra' );
+            my $onissue = 0;
+            foreach my $item (@items) {
+                if ( $item->{'datedue'} eq 'Reserved' ) {
+                    $onissue = 0;
+                    if ($item->{'branchname'} eq ''){
+                        $line{'status'}='In Transit';
+                    }
+                    else {                      
+                        $line{'status'} = "On shelf at $item->{'branchname'}";
+                    }
+                    
+                }
+                
+                else {
+                    $onissue = 1;
+                }
+            }           
+            if ($onissue) {
+                $line{'status'} = 'On Issue';
+            }
+        }
+        else {
+            $line{'status'}="Waiting for pickup";
+            
+        }
+     }
     push( @dataloop, \%line );
 }
 
+if ($sort eq 'name'){ 
+    @dataloop = sort {$a->{'surname'} cmp $b->{'surname'}} @dataloop;                                                                                         
+}                                                                                                                                                             
+elsif ($sort eq 'date'){                                                                                                                                      
+    @dataloop = sort {$a->{'sortdate'} cmp $b->{'sortdate'}} @dataloop;                                                                                       
+}                                                                                                                                                             
+elsif ($sort eq 'title'){                                                                                                                                     
+    @dataloop = sort {$a->{'title'} cmp $b->{'title'}} @dataloop;                                                                                             
+}                                                                                                                                                             
+else {                                                                                                                                                        
+    @dataloop = sort {$a->{'status'} cmp $b->{'status'}} @dataloop;                                                                                           
+}                                                                                                                                                             
+
 
 $template->param(
     count    => $count,
-    dataloop => \@dataloop
+    dataloop => \@dataloop,
+    branchcode => $branch,
+    branchloop => \@branchloop
+    
 );
 
 output_html_with_http_headers $input, $cookie, $template->output;
index 2a6df6a..8df2ea7 100755 (executable)
@@ -3,7 +3,7 @@
 use strict;
 use CGI;
 use C4::Output;
-use HTML::Template;
+
 use C4::Auth;
 use C4::Interface::CGI::Output;
 use C4::Context;
@@ -23,6 +23,7 @@ my $csv = Text::CSV_XS->new(
 
 my $input=new CGI;
 my $time=$input->param('time');
+my $time2=$input->param('time2');
 
 my @loop1;
 my @loop2;
@@ -56,6 +57,10 @@ if ($time eq ''){
         $date2=ParseDate('tomorrow');
 }
 
+if ($time2 ne ''){
+            $date=ParseDate($time);
+            $date2=ParseDate($time2);
+}
 
 my $date=UnixDate($date,'%Y-%m-%d');
 my $date2=UnixDate($date2,'%Y-%m-%d');
@@ -94,7 +99,8 @@ while ($i<$count ){
                my $sec=substr($payments[$i]{'timestamp'},12,2);
                my $time="$hour:$min:$sec";
                my $time2="$payments[$i]{'date'}";
-               my $branch=Getpaidbranch($time2,$payments[$i]{'borrowernumber'});
+#               my $branch=Getpaidbranch($time2,$payments[$i]{'borrowernumber'});
+              my $branch=$payments[$i]{'branch'};
 
                my @rows1 = ($branch,          # lets build up a row
                             $payments[$i]->{'datetime'},
@@ -102,17 +108,19 @@ while ($i<$count ){
                             $payments[$i]->{'firstname'},
                             $charges[$i2]->{'description'},
                             $charges[$i2]->{'accounttype'},
-                            sprintf("%.2f", $charges[$i2]->{'amount'}), # rounding amounts to 2dp
+   # rounding amounts to 2dp and adding dollar sign to make excel read it as currency format
+                            "\$".sprintf("%.2f", $charges[$i2]->{'amount'}), 
                             $payments[$i]->{'type'},
-                            $payments[$i]->{'value'});
+                            "\$".$payments[$i]->{'value'});
 
                push (@loop1, \@rows1);
+              $totalpaid = $totalpaid + $payments[$i]->{'value'};
            }
        } else {
          ++$totalwritten;
        }
+
        $i++; #increment the while loop
-       $totalpaid = $totalpaid + $payments[$i]->{'value'};
 }
 
 #get credits and append to the bottom of payments
@@ -129,11 +137,11 @@ while ($i<$count ){
                     $credits[$i]->{'firstname'},
                     $credits[$i]->{'description'},
                     $credits[$i]->{'accounttype'},
-                    $credits[$i]->{'amount'});
+                    "\$".$credits[$i]->{'amount'});
 
        push (@loop2, \@rows2);
-       $i++;
        $totalcredits = $totalcredits + $credits[$i]->{'amount'};
+       $i++;
 }
 
 #takes off first char minus sign "-100.00"
@@ -141,9 +149,9 @@ $totalcredits = substr($totalcredits, 1);
 
 print $input->header(
     -type       => 'application/vnd.ms-excel',
-    -attachment => "moo.csv",         
+    -attachment => "stats.csv",
 );
-print "Branch, Datetime, Surame, Firstnames, Description, Type, Invoice amount, Payment type, Payment Amount\n";
+print "Branch, Datetime, Surname, Firstnames, Description, Type, Invoice amount, Payment type, Payment Amount\n";
 
 
 for my $row ( @loop1 ) {
@@ -167,3 +175,4 @@ print ",,,,,,,\n";
 print ",,Total Amount Paid, $totalpaid\n";
 print ",,Total Number Written, $totalwritten\n";
 print ",,Total Amount Credits, $totalcredits\n";
+
index dfa6e71..e2fd380 100755 (executable)
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 use CGI;
 use C4::Output;
-use HTML::Template;
 use C4::Auth;
 use C4::Interface::CGI::Output;
 use C4::Context;
 use Date::Manip;
-use C4::Date;
 use C4::Stats;
-&Date_Init("DateFormat=non-US"); # set non-USA date, eg:19/08/2005
-
-my $input=new CGI;
-my $time=$input->param('time');
-my $date=$input->param('from');
-my $date2=$input->param('to');
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "reports/stats.screen.tmpl",
-                             query => $input,
-                             type => "intranet",
-                             authnotrequired => 0,
-                             flagsrequired => {borrowers => 1},
-                             debug => 1,
-                             });
-
-
-#get a list of every payment
-my @payments=TotalPaid($date,$date2);
-
-my $count=@payments;
-# warn "number of payments=$count\n";
-
-my $i=0;
-my $totalcharges=0;
-my $totalcredits=0;
-my $totalpaid=0;
-my $totalwritten=0;
-my $totalwrittenamount=0;
-my $totalinvoicesamount=0;
-my $totalinvoices=0;
-my @loop1;
-my @loop2;
-my @loop3;
 
-# lets get a a list of all individual item charges paid for by that payment
-while ($i<$count ){
+&Date_Init("DateFormat=non-US");    # set non-USA date, eg:19/08/2005
 
-       my $count;
-       my @charges;
+my $input = new CGI;
+my $time  = $input->param('time');
+my $time2 = $input->param('time2');
 
-       if ($payments[$i]->{'accounttype'} ne 'W'){         # lets ignore writeoff payments!.
-           @charges=getcharges($payments[$i]{'borrowernumber'}, $payments[$i]{'offset'}, $payments[$i]{'accountno'});
-           $totalcharges++;
-           $count=@charges;
+if (   $input->param('submit') eq "To Excel"
+    || $input->param('submit_x') eq "To Excel" )
+{
+    print $input->redirect(
+        "/cgi-bin/koha/stats.print.pl?time=$time&time2=$time2");
+}
 
-           # getting each of the charges and putting them into a array to be printed out
-           #this loops per charge per person
-           for (my $i2=0;$i2<$count;$i2++){
-              
-               my $time2="$payments[$i]{'date'}";
-#               my $branch=Getpaidbranch($time2,$payments[$i]{'borrowernumber'});
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "stats_screen.tmpl",
+        query           => $input,
+        type            => "intranet",
+        authnotrequired => 1,
+        flagsrequired   => { reports => 1 },
+        debug           => 1,
+    }
+);
+
+my $date;
+my $date2;
+if ( $time eq 'yesterday' ) {
+    $date  = ParseDate('yesterday');
+    $date2 = ParseDate('today');
+}
+if ( $time eq 'today' ) {
+    $date  = ParseDate('today');
+    $date2 = ParseDate('tomorrow');
+}
+if ( $time eq 'daybefore' ) {
+    $date  = ParseDate('2 days ago');
+    $date2 = ParseDate('yesterday');
+}
+if ( $time eq 'month' ) {
+    $date  = ParseDate('1 month ago');
+    $date2 = ParseDate('today');
 
-               # lets build up a row
-               my %rows1 = ( datetime => $payments[$i]->{'timestamp'},
-                            surname => $payments[$i]->{'surname'},
-                            firstname => $payments[$i]->{'firstname'},
-                            description => $payments[$i]->{'description'},
-                            accounttype => $charges[$i2]->{'accounttype'},
-                            amount => sprintf("%.2f",  $charges[$i2]->{'amount'}), # rounding amounts to 2dp
-                            type => $payments[$i]->{'accounttype'},
-                            value => sprintf("%.2f", $payments[$i]->{'amount'}*(-1))); # rounding amounts to 2dp
-
-               push (@loop1, \%rows1);
-  $totalpaid = sprintf("%.2f",$totalpaid + $payments[$i]->{'amount'}*(-1));
-           }
-       } else {
-$totalwrittenamount= sprintf("%.2f",$totalwrittenamount + $payments[$i]->{'amount'}*(-1));
-         ++$totalwritten;
-       }
-      
-     
- $i++; #increment the while loop
+}
+if ( $time =~ /\// ) {
+    $date  = ParseDate($time);
+    $date2 = ParseDateDelta('+ 1 day');
+    $date2 = DateCalc( $date, $date2 );
 }
 
-#get credits and append to the bottom of payments
-my @credits=getcredits($date,$date2);
+# if time is blank
+if ( $time eq '' ) {
+    $date  = ParseDate('today');
+    $date2 = ParseDate('tomorrow');
+}
 
-my $count=@credits;
-my $i=0;
+# if script is called with a start and finsh date range...
+if ( $time ne '' && $time2 ne '' ) {
+    $date  = ParseDate($time);
+    $date2 = ParseDate($time2);
+}
 
-while ($i<$count ){
+my $date  = UnixDate( $date,  '%Y-%m-%d' );
+my $date2 = UnixDate( $date2, '%Y-%m-%d' );
 
-       my %rows2 = (creditdate          => format_date($credits[$i]->{'date'}),
-                    creditsurname       => $credits[$i]->{'surname'},
-                    creditfirstname     => $credits[$i]->{'firstname'},
-                    creditdescription   => $credits[$i]->{'description'},
-                    creditaccounttype   => $credits[$i]->{'accounttype'},
-                    creditamount        => sprintf("%.2f",$credits[$i]->{'amount'}*(-1)));
+# warn "MASON: TIME: $time, $time2";
+# warn "MASON: DATE: $date, $date2";
 
-       push (@loop2, \%rows2);
-    
-       $totalcredits =sprintf("%.2f", $totalcredits + $credits[$i]->{'amount'});
-         $i++; #increment the while loop
+# get a list of every payment
+my @payments = TotalPaid( $date, $date2, 0 );
 
+my $count = @payments;
+
+# print "MASON: number of payments=$count\n";
+
+my $i            = 0;
+my $totalcharges = 0;
+my $totalcredits = 0;
+my $totalpaid    = 0;
+my $totalwritten = 0;
+my @loop1;
+my @loop2;
+
+# lets get a a list of all individual item charges paid for by that payment
+while ( $i < $count ) {
+
+    my $count;
+    my @charges;
+
+    if ( $payments[$i]{'type'} ne 'writeoff' ) {
+
+        @charges = getcharges(
+            $payments[$i]{'borrowernumber'},
+            $payments[$i]{'timestamp'},
+            $payments[$i]{'proccode'}
+        );
+        $totalcharges++;
+        $count = @charges;
+
+   # getting each of the charges and putting them into a array to be printed out
+   #this loops per charge per person
+        for ( my $i2 = 0 ; $i2 < $count ; $i2++ ) {
+            my $hour = substr( $payments[$i]{'timestamp'}, 8,  2 );
+            my $min  = substr( $payments[$i]{'timestamp'}, 10, 2 );
+            my $sec  = substr( $payments[$i]{'timestamp'}, 12, 2 );
+            my $time = "$hour:$min:$sec";
+            my $time2 = "$payments[$i]{'date'}";
+
+#               my $branch=Getpaidbranch($time2,$payments[$i]{'borrowernumber'});
+            my $branch = $payments[$i]{'branch'};
+
+#             if ($payments[$i]{'borrowernumber'} == 18265){
+#               warn "$payments[$i]{'branch'} $branch $payments[$i]{'borrowernumber'}";#
+#                 }
+# lets build up a row
+            my %rows1 = (
+                branch      => $branch,
+                datetime    => $payments[$i]->{'datetime'},
+                surname     => $payments[$i]->{'surname'},
+                firstname   => $payments[$i]->{'firstname'},
+                description => $charges[$i2]->{'description'},
+                accounttype => $charges[$i2]->{'accounttype'},
+                amount      => sprintf( "%.2f", $charges[$i2]->{'amount'} )
+                ,    # rounding amounts to 2dp
+                type  => $payments[$i]->{'type'},
+                value => sprintf( "%.2f", $payments[$i]->{'value'} )
+            );       # rounding amounts to 2dp
+
+            push( @loop1, \%rows1 );
+            $totalpaid = $totalpaid + $payments[$i]->{'value'};
+        }
+    }
+    else {
+        ++$totalwritten;
+    }
+
+    $i++;            #increment the while loop
 }
 
+#get credits and append to the bottom of payments
+my @credits = getcredits( $date, $date2 );
+
+my $count = @credits;
+my $i     = 0;
+
+while ( $i < $count ) {
+
+    my %rows2 = (
+        creditbranch      => $credits[$i]->{'branchcode'},
+        creditdate        => $credits[$i]->{'date'},
+        creditsurname     => $credits[$i]->{'surname'},
+        creditfirstname   => $credits[$i]->{'firstname'},
+        creditdescription => $credits[$i]->{'description'},
+        creditaccounttype => $credits[$i]->{'accounttype'},
+        creditamount      => sprintf( "%.2f", $credits[$i]->{'amount'} )
+    );
+
+    push( @loop2, \%rows2 );
+    $totalcredits = $totalcredits + $credits[$i]->{'amount'};
+    $i++;    #increment the while loop
+}
 
 #takes off first char minus sign "-100.00"
-$totalcredits = substr($totalcredits, 1);
-
-my @invoices=getinvoices($date,$date2);
-my $count=@invoices;
-my $i=0;
-
-while ($i<$count ){
-
-       my %rows3 = (invoicesdate          => format_date($invoices[$i]->{'date'}),
-                   invoicessurname       => $invoices[$i]->{'surname'},
-                   invoicesfirstname     => $invoices[$i]->{'firstname'},
-                    invoicesdescription   => $invoices[$i]->{'description'},
-                    invoicesaccounttype   => $invoices[$i]->{'accounttype'},
-                    invoicesamount        => sprintf("%.2f",$invoices[$i]->{'amount'}),
-       invoicesamountremaining=>sprintf("%.2f",$invoices[$i]->{'amountoutstanding'}));
-       push (@loop3, \%rows3);
-         $totalinvoicesamount =sprintf("%.2f", $totalinvoicesamount + $invoices[$i]->{'amountoutstanding'});
-       $totalinvoices =sprintf("%.2f", $totalinvoices + $invoices[$i]->{'amount'});
-         $i++; #increment the while loop
+$totalcredits = substr( $totalcredits, 1 );
 
+my $totalrefunds = 0;
+my @loop3;
+my @refunds = getrefunds( $date, $date2 );
+$count = @refunds;
+$i     = 0;
+
+while ( $i < $count ) {
+
+    my %rows2 = (
+        refundbranch      => $refunds[$i]->{'branchcode'},
+        refunddate        => $refunds[$i]->{'date'},
+        refundsurname     => $refunds[$i]->{'surname'},
+        refundfirstname   => $refunds[$i]->{'firstname'},
+        refunddescription => $refunds[$i]->{'description'},
+        refundaccounttype => $refunds[$i]->{'accounttype'},
+        refundamount      => sprintf( "%.2f", $refunds[$i]->{'amount'} )
+    );
+
+    push( @loop3, \%rows2 );
+    $totalrefunds = $totalrefunds + $refunds[$i]->{'amount'};
+    $i++;    #increment the while loop
 }
-$template->param( loop1               => \@loop1,
-                  loop2               => \@loop2,
-                loop3               => \@loop3,
-                  totalpaid           => $totalpaid,
-                  totalcredits        => $totalcredits,
-               totalcreditsamount        => sprintf("%.2f",$totalcredits-$totalwrittenamount),
-       totalwrittenamount        => $totalwrittenamount,
-                  totalwritten        => $totalwritten ,
-       totalinvoices=>$totalinvoices, totalinvoicesamount=>$totalinvoicesamount        );
+
+my $totalcash = $totalpaid - $totalrefunds;
+
+$template->param(
+    date         => $time,
+    date2        => $time2,
+    loop1        => \@loop1,
+    loop2        => \@loop2,
+    loop3        => \@loop3,
+    totalpaid    => $totalpaid,
+    totalcredits => $totalcredits,
+    totalwritten => $totalwritten,
+    totalrefund  => $totalrefunds,
+    totalcash    => $totalcash
+);
 
 output_html_with_http_headers $input, $cookie, $template->output;
+
index 0d74f7e..54d15b0 100755 (executable)
 # Suite 330, Boston, MA  02111-1307 USA
 
 use strict;
-#use DBI;
-use C4::Search;
 use CGI;
 use C4::Output;
 use C4::Reserves2;
-use C4::Members;
+
 my $input = new CGI;
 #print $input->header;
 
-#print $input->Dump;
-
 my @rank=$input->param('rank-request');
 my @biblionumber=$input->param('biblionumber');
 my @borrower=$input->param('borrowernumber');
 my @branch=$input->param('pickup');
+my @itemnumber=$input->param('itemnumber');
 my $count=@rank;
-my $cataloger=$input->param('loggedinuser');
-# goes through and manually changes the reserves record....
-# no attempt is made to check consistency.
-for (my $i=0;$i<$count;$i++){
-    UpdateReserves($rank[$i],$biblionumber[$i],$borrower[$i],$branch[$i],$cataloger); #from C4::Reserves2
+
+my $CancelBiblioNumber=$input->param('CancelBiblioNumber');
+my $CancelBorrowerNumber=$input->param('CancelBorrowerNumber');
+my $CancelItemnumber=$input->param('CancelItemnumber');
+
+# 2 possibilitys : cancel an item reservation, or modify or cancel the queded list
+
+# 1) cancel an item reservation by fonction GlobalCancel (in reserves2.pm)
+if ($CancelBorrowerNumber) {
+       GlobalCancel($CancelItemnumber, $CancelBorrowerNumber);
+       $biblionumber[0] = $CancelBiblioNumber,
 }
 
+# 2) Cancel or modify the queue list of reserves (without item linked)
+else {
+       for (my $i=0;$i<$count;$i++){
+               UpdateReserve($rank[$i],$biblionumber[$i],$borrower[$i],$branch[$i],$itemnumber[$i]); #from C4::Reserves2
+       }
+}
 my $from=$input->param('from');
 if ($from eq 'borrower'){
-  print $input->redirect("/cgi-bin/koha/members/moremember.pl?bornum=$borrower[0]");
+  print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrower[0]");
  } else {
    print $input->redirect("/cgi-bin/koha/reserve/request.pl?biblionumber=$biblionumber[0]");
 }
index eaafca1..004fca8 100755 (executable)
 # Suite 330, Boston, MA  02111-1307 USA
 
 use strict;
-#use DBI;
-use C4::Search;
+use C4::Biblio;
 use CGI;
 use C4::Output;
 use C4::Reserves2;
+use C4::Circulation::Circ2;
 use C4::Members;
+
 my $input = new CGI;
 #print $input->header;
-my $itemnumber=$input->param('itemnumber');
+
 my @bibitems=$input->param('biblioitem');
 my @reqbib=$input->param('reqbib');
 my $biblionumber=$input->param('biblionumber');
@@ -40,38 +41,52 @@ my $branch=$input->param('pickup');
 my @rank=$input->param('rank-request');
 my $type=$input->param('type');
 my $title=$input->param('title');
-my $bornum=borrdata($borrower,'');
-my $cataloger=$input->param('loggedinuser');
-
-if ($type eq 'str8' && $bornum ne ''){
-    my $count=@bibitems;
-    @bibitems=sort @bibitems;
-    my $i2=1;
-    my @realbi;
-    $realbi[0]=$bibitems[0];
-for (my $i=1;$i<$count;$i++){
-    my $i3=$i2-1;
-    if ($realbi[$i3] ne $bibitems[$i]){
-       $realbi[$i2]=$bibitems[$i];
-       $i2++;
-    }
-}
+my $borrowernumber=borrdata($borrower,'');
+my $checkitem=$input->param('checkitem');
+my $found;
 
-my $env;
+#new op : if we have an item selectionned, and the pickup branch is the same as the holdingbranch of the document, we force the value $rank and $found .
+if ($checkitem ne ''){
+               $rank[0] = '0';
+               my $item = $checkitem;
+               $item = getiteminformation($item);
+               if ( $item->{'holdingbranch'} eq $branch ){
+               $found = 'W';   
+               }
 
-my $const;
 
-
-for (my $i=0; $i<@reqbib; $i++){
-if ($reqbib[$i] ne ''){
-  $const='o';
-  CreateReserve(\$env,$bornum->{'borrowernumber'},$cataloger,$biblionumber,'','',$branch,$const,$rank[0],$notes,$title,"",$reqbib[$i]);
-}
 }
 
+# END of new op .
+
+if ($type eq 'str8' && $borrowernumber ne ''){
+       my $count=@bibitems;
+       @bibitems=sort @bibitems;
+       my $i2=1;
+       my @realbi;
+       $realbi[0]=$bibitems[0];
+       for (my $i=1;$i<$count;$i++) {
+               my $i3=$i2-1;
+               if ($realbi[$i3] ne $bibitems[$i]) {
+                       $realbi[$i2]=$bibitems[$i];
+                       $i2++;
+               }
+       }
+       my $env;
+       my $const;
+       if ($input->param('request') eq 'any'){
+       $const='a';
+  CreateReserve(\$env,$branch,$borrowernumber->{'borrowernumber'},$biblionumber,$const,\@realbi,$rank[0],$notes,$title,$checkitem,$found);
+       } elsif ($reqbib[0] ne ''){
+       $const='o';
+  CreateReserve(\$env,$branch,$borrowernumber->{'borrowernumber'},$biblionumber,$const,\@reqbib,$rank[0],$notes,$title,$checkitem, $found);
+       } else {
+  CreateReserve(\$env,$branch,$borrowernumber->{'borrowernumber'},$biblionumber,'a',\@realbi,$rank[0],$notes,$title,$checkitem, $found);
+       }
+       
 print $input->redirect("request.pl?biblionumber=$biblionumber");
-} elsif ($bornum eq ''){
-  print $input->header();
-  print "Invalid card number please try again";
-  print $input->Dump;
+} elsif ($borrowernumber eq ''){
+       print $input->header();
+       print "Invalid card number please try again";
+       print $input->Dump;
 }
index 03d59a0..e26fc14 100755 (executable)
@@ -2,10 +2,7 @@
 
 # $Id$
 
-#script to place reserves/requests
 #writen 2/1/00 by chris@katipo.oc.nz
-
-
 # Copyright 2000-2002 Katipo Communications
 #
 # This file is part of Koha.
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
+=head1 request.pl
+
+script to place reserves/requests
+
+=cut
+
 use strict;
-use C4::Search;
+use C4::Branch; # GetBranches get_branchinfos_of
+use CGI;
+use List::MoreUtils qw/uniq/;
+use Date::Calc qw/Today Date_to_Days/;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Auth;
@@ -32,174 +38,401 @@ use C4::Reserves2;
 use C4::Biblio;
 use C4::Koha;
 use C4::Circulation::Circ2;
-use C4::Acquisition;
-use CGI;
 use C4::Date;
+use C4::Members;
 
+my $dbh = C4::Context->dbh;
+my $sth;
 my $input = new CGI;
-my $dbh=C4::Context->dbh;
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "reserve/request.tmpl",
+        query           => $input,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { reserveforothers => 1 },
+    }
+);
+
 # get biblio information....
 my $biblionumber = $input->param('biblionumber');
-my ($record) = XMLgetbiblio($dbh,$biblionumber);
-$record=XML_xml2hash_onerecord($record);
-my $dat=XMLmarc2koha_onerecord($dbh,$record,"biblios");
+my $dat          = GetBiblioData($biblionumber);
+
+# Select borrowers infos
+my $findborrower = $input->param('findborrower');
+$findborrower =~ s|,| |g;
+my $cardnumber = $input->param('cardnumber');
+my %env;
+my $borrowerslist;
+my $messageborrower;
+
+my $date = sprintf( '%04d-%02d-%02d', Today() );
+
+if ($findborrower) {
+    my ( $count, $borrowers ) =
+      BornameSearch( \%env, $findborrower, 'cardnumber', 'web' );
+
+    my @borrowers = @$borrowers;
+
+    if ( $#borrowers == -1 ) {
+        $input->param( 'findborrower', '' );
+        $messageborrower = "'$findborrower'";
+    }
+    elsif ( $#borrowers == 0 ) {
+        $input->param( 'cardnumber', $borrowers[0]->{'cardnumber'} );
+        $cardnumber = $borrowers[0]->{'cardnumber'};
+    }
+    else {
+        $borrowerslist = \@borrowers;
+    }
+}
+
+if ($cardnumber) {
+    my $borrowerinfo = getpatroninformation( \%env, 0, $cardnumber );
+    my $expiry;
+    my $diffbranch;
+    my @getreservloop;
+    my $count_reserv = 0;
+    my $maxreserves;
+
+#      we check the reserves of the borrower, and if he can reserv a document
+# FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
+
+    my $number_reserves =
+      CountReservesFromBorrower( $borrowerinfo->{'borrowernumber'} );
+
+    if ( $number_reserves > C4::Context->preference('maxreserves') ) {
+        $maxreserves = 1;
+    }
+
+    # we check the date expiricy of the borrower
+    my $warning = (Date_to_Days(split /-/,$date) > Date_to_Days( split /-/,$borrowerinfo->{'dateexpiry'}));
+     
+    if ( $warning > 0 ) {
+        $expiry = 1;
+    }
+
+    # check if the borrower make the reserv in a different branch
+    if ( $borrowerinfo->{'branchcode'} ne C4::Context->userenv->{'branch'} ) {
+        $diffbranch = 1;
+    }
+
+    $template->param(
+        borrowersurname   => $borrowerinfo->{'surname'},
+        borrowerfirstname => $borrowerinfo->{'firstname'},
+        borrowerreservs   => $count_reserv,
+        maxreserves       => $maxreserves,
+        expiry            => $expiry,
+        diffbranch        => $diffbranch
+    );
+}
+
+$template->param( messageborrower => $messageborrower );
+
+my $CGIselectborrower;
+if ($borrowerslist) {
+    my @values;
+    my %labels;
+
+    foreach my $borrower (
+        sort {
+                $a->{surname}
+              . $a->{firstname} cmp $b->{surname}
+              . $b->{firstname}
+        } @{$borrowerslist}
+      )
+    {
+        push @values, $borrower->{cardnumber};
+
+        $labels{ $borrower->{cardnumber} } = sprintf(
+            '%s, %s ... (%s - %s) ... %s',
+            $borrower->{surname},    $borrower->{firstname},
+            $borrower->{cardnumber}, $borrower->{categorycode},
+            $borrower->{streetaddress},
+        );
+    }
+
+    $CGIselectborrower = CGI::scrolling_list(
+        -name     => 'cardnumber',
+        -values   => \@values,
+        -labels   => \%labels,
+        -size     => 7,
+        -multiple => 0,
+    );
+}
+
 # get existing reserves .....
-my ($count,$reserves) = FindReserves($biblionumber);
+my ( $count, $reserves ) = FindReserves($biblionumber);
 my $totalcount = $count;
+my $alreadyreserved;
+
+# FIXME launch another time getpatroninformation perhaps until
+my $borrowerinfo = getpatroninformation( \%env, 0, $cardnumber );
+
 foreach my $res (@$reserves) {
-    if ($res->{'found'} eq 'W') {
-       $count--;
+    if ( ( $res->{found} eq 'W' ) or ( $res->{priority} == 0 ) ) {
+        $count--;
+    }
+
+    if ( $borrowerinfo->{borrowernumber} eq $res->{borrowernumber} ) {
+        $alreadyreserved = 1;
     }
 }
 
+$template->param( alreadyreserved => $alreadyreserved );
+
+# FIXME think @optionloop, is maybe obsolete, or  must be switchable by a systeme preference fixed rank or not
 # make priorities options
-my $num = $count + 1;
 
-#priorityoptions building
 my @optionloop;
-for (my $i=1; $i<=$num; $i++){
-       my %option;
-       $option{num}=$i;
-       $option{selected}=($i==$num);
-       push(@optionloop, \%option);
+for ( 1 .. $count + 1 ) {
+    push(
+        @optionloop,
+        {
+            num      => $_,
+            selected => ( $_ == $count + 1 ),
+        }
+    );
 }
+# adding a fixed value for priority options
+my $fixedRank = $count+1;
+
+my @branchcodes;
+my %itemnumbers_of_biblioitem;
+my @itemnumbers  = @{ get_itemnumbers_of($biblionumber)->{$biblionumber} };
+my $iteminfos_of = GetItemInfosOf(@itemnumbers);
+
+foreach my $itemnumber (@itemnumbers) {
+    push( @branchcodes,
+        $iteminfos_of->{$itemnumber}->{homebranch},
+        $iteminfos_of->{$itemnumber}->{holdingbranch} );
+
+    my $biblioitemnumber = $iteminfos_of->{$itemnumber}->{biblioitemnumber};
+    push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
+}
+
+@branchcodes = uniq @branchcodes;
 
-# todays date
-my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =localtime(time);
-$year=$year+1900;
-$mon++;
-my $date=format_date("$year-$mon-$mday");
+my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
+
+my $branchinfos_of      = get_branchinfos_of(@branchcodes);
+my $notforloan_label_of = get_notforloan_label_of();
+my $biblioiteminfos_of  = GetBiblioItemInfosOf(@biblioitemnumbers);
+
+my @itemtypes;
+foreach my $biblioitemnumber (@biblioitemnumbers) {
+    push @itemtypes, $biblioiteminfos_of->{$biblioitemnumber}{itemtype};
+}
+
+my $itemtypeinfos_of = get_itemtypeinfos_of(@itemtypes);
+
+my $return_date_of = get_current_return_date_of(@itemnumbers);
 
 my @bibitemloop;
 
-       my %abibitem;
-       my @barcodeloop;
-    my @barcodes = barcodes($biblionumber);
-#warn @barcodes;
-    foreach my $num (@barcodes) {
-               my %barcode;
-               $barcode{'date_due'}=$num->{'date_due'} if $num->{'date_due'} gt "0000-00-00" ;
-               $barcode{'barcode'}=$num->{'barcode'};
-               $barcode{'itemnumber'}=$num->{'itemnumber'};
-               $barcode{'message'}=$num->{'itemlost'} == 1 ? "(lost)" :
-               $num->{'itemlost'} == 2 ? "(long overdue)" : "";
-               $barcode{'class'}=$num->{'itemcallnumber'};
-               $abibitem{'itemlost'}=(($num->{'notforloan'})|| ($num->{'itemlost'} == 1)) ;
-               $abibitem{'itemlost'}=($num->{'wthdrawn'}) ;
-               push(@barcodeloop, \%barcode);
-    }
-#      
-       $abibitem{'class'}="$dat->{'classification'}$dat->{'dewey'}$dat->{'subclass'}";
-       $abibitem{'biblionumber'}=$dat->{'biblionumber'};
-       $abibitem{'description'}=$dat->{'itemtype'};
-       $abibitem{'volumeddesc'}=$dat->{'volumeddesc'};
-       $abibitem{'publicationyear'}=$dat->{'publicationyear'};
+foreach my $biblioitemnumber (@biblioitemnumbers) {
+    my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
+
+    $biblioitem->{description} =
+      $itemtypeinfos_of->{ $biblioitem->{itemtype} }{description};
+
+    foreach
+      my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )
+    {
+        my $item = $iteminfos_of->{$itemnumber};
+
+        $item->{homebranchname} =
+          $branchinfos_of->{ $item->{homebranch} }{branchname};
 
-       $abibitem{'barcodeloop'}=\@barcodeloop;
-       push(@bibitemloop,\%abibitem);
+        # if the holdingbranch is different than the homebranch, we show the
+        # holdingbranch of the document too
+        if ( $item->{homebranch} ne $item->{holdingbranch} ) {
+            $item->{holdingbranchname} =
+              $branchinfos_of->{ $item->{holdingbranch} }{branchname};
+        }
+        
+#      add inforrmation
+       $item->{itemcallnumber} = $item->{itemcallnumber};
+       
+        # if the item is currently on loan, we display its return date and
+        # change the background color
+        my $date_due;
 
+        if ( defined $return_date_of->{$itemnumber} ) {
+            $date_due = format_date( $return_date_of->{$itemnumber} );
+            $item->{date_due} = $date_due;
+            $item->{backgroundcolor} = 'onloan';
+        }
 
+        # checking reserve
+        my ($reservedate,$reservedfor,$expectedAt) = GetFirstReserveDateFromItem($itemnumber);
+        my $ItemBorrowerReserveInfo = getpatroninformation( \%env, $reservedfor, 0);
 
+        if ( defined $reservedate ) {
+            $item->{backgroundcolor} = 'reserved';
+            $item->{reservedate}     = format_date($reservedate);
+            $item->{ReservedForBorrowernumber}     = $reservedfor;
+            $item->{ReservedForSurname}     = $ItemBorrowerReserveInfo->{'surname'};
+            $item->{ReservedForFirstname}     = $ItemBorrowerReserveInfo->{'firstname'};
+            $item->{ExpectedAtLibrary}     = $expectedAt;
+            
+        }
 
-#existingreserves building
+        # Management of the notforloan document
+        if ( $item->{notforloan} ) {
+            $item->{backgroundcolor} = 'other';
+            $item->{notforloanvalue} =
+              $notforloan_label_of->{ $item->{notforloan} };
+        }
+
+        # Management of lost or long overdue items
+        if ( $item->{itemlost} ) {
+
+            # FIXME localized strings should never be in Perl code
+            $item->{message} =
+                $item->{itemlost} == 1 ? "(lost)"
+              : $item->{itemlost} == 2 ? "(long overdue)"
+              : "";
+            $item->{backgroundcolor} = 'other';
+        }
+
+        # Check of the transfered documents
+        my ( $transfertwhen, $transfertfrom, $transfertto ) =
+          get_transfert_infos($itemnumber);
+
+        if ( $transfertwhen ne '' ) {
+            $item->{transfertwhen} = format_date($transfertwhen);
+            $item->{transfertfrom} =
+              $branchinfos_of->{$transfertfrom}{branchname};
+            $item->{transfertto} = $branchinfos_of->{$transfertto}{branchname};
+               $item->{nocancel} = 1;
+        }
+
+        # If there is no loan, return and transfer, we show a checkbox.
+        $item->{notforloan} = $item->{notforloan} || 0;
+
+        # An item is available only if:
+        if (
+            not defined $reservedate    # not reserved yet
+            and $date_due eq ''         # not currently on loan
+            and not $item->{itemlost}   # not lost
+            and not $item->{notforloan} # not forbidden to loan
+            and $transfertwhen eq ''    # not currently on transfert
+          )
+        {
+            $item->{available} = 1;
+        }
+
+        push @{ $biblioitem->{itemloop} }, $item;
+    }
+
+    push @bibitemloop, $biblioitem;
+}
+
+# existingreserves building
 my @reserveloop;
 my $branches = GetBranches();
+my ( $count, $reserves ) = FindReservesInQueue($biblionumber);
+foreach my $res ( sort { $a->{found} cmp $b->{found} } @$reserves ) {
+    my %reserve;
+    my @optionloop;
+    for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
+        push(
+            @optionloop,
+            {
+                num      => $i,
+                selected => ( $i == $res->{priority} ),
+            }
+        );
+    }
+    my @branchloop;
+    foreach my $br ( keys %$branches ) {
+        my %abranch;
+        $abranch{'selected'}   = ( $br eq $res->{'branchcode'} );
+        $abranch{'branch'}     = $br;
+        $abranch{'branchname'} = $branches->{$br}->{'branchname'};
+        push( @branchloop, \%abranch );
+    }
 
-foreach my $res (sort {$a->{'found'} cmp $b->{'found'}} @$reserves){
-       my %reserve;
-if ($res->{'priority'}>$totalcount){$totalcount=$res->{'priority'};}
-#    my $prioropt = priorityoptions($totalcount, $res->{'priority'});
-       my @optionloop;
-       for (my $i=1; $i<=$totalcount; $i++){
-               my %option;
-               $option{num}=$i;
-               $option{selected}=($i==$res->{'priority'});
-               push(@optionloop, \%option);
-       }
-       my @branchloop;
-
-       foreach my $br (keys %$branches) {
-
-
-
-               (next) unless $branches->{$br}->{'IS'};
-
-                               # Only branches with the 'IS' branchrelation
-                               # can issue books
-               my %abranch;
-               $abranch{'selected'}=($br eq $res->{'branchcode'});
-               $abranch{'branch'}=$br;
-               $abranch{'branchname'}=$branches->{$br}->{'branchname'};
-               push(@branchloop,\%abranch);
-       }
-my %env;
-#              my $item = $res->{'itemnumber'};
-#              $item = getiteminformation(\%env,$item);
-
-    if ($res->{'found'} eq 'W') {
-               
-               $reserve{'holdingbranch'}=$res->{'holdingbranch'};
-               $reserve{'barcode'}=$res->{'barcode'};
-               $reserve{'biblionumber'}=$res->{'biblionumber'};
-               $reserve{'wbrcode'} = $res->{'branchcode'};
-               $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
-               if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
-                       $reserve{'atdestination'} = 1;
-               }
+    if ( ( $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) ) {
+        my %env;
+        my $item = $res->{'itemnumber'};
+        $item = getiteminformation($item,undef);
+        $reserve{'wait'}= 1; 
+        $reserve{'holdingbranch'}=$item->{'holdingbranch'};
+        $reserve{'biblionumber'}=$item->{'biblionumber'};
+        $reserve{'barcodenumber'}      = $item->{'barcode'};
+        $reserve{'wbrcode'} = $res->{'branchcode'};
+        $reserve{'itemnumber'} = $res->{'itemnumber'};
+        $reserve{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
+        if($reserve{'holdingbranch'} eq $reserve{'wbrcode'}){
+            $reserve{'atdestination'} = 1;
+        }
     }
-       $reserve{'barcode'}=$res->{'barcode'};
-       $reserve{'date'} = format_date($res->{'reservedate'});
-       $reserve{'borrowernumber'}=$res->{'borrowernumber'};
-       $reserve{'biblionumber'}=$res->{'biblionumber'};
-       $reserve{'bornum'}=$res->{'borrowernumber'};
-       $reserve{'firstname'}=$res->{'firstname'};
-       $reserve{'surname'}=$res->{'surname'};
-       $reserve{'bornum'}=$res->{'borrowernumber'};
-       $reserve{'notes'}=$res->{'reservenotes'};
-       $reserve{'wait'}=($res->{'found'} eq 'W');
-       $reserve{'constrainttypea'}=($res->{'constrainttype'} eq 'a');
-       $reserve{'constrainttypeo'}=($res->{'constrainttype'} eq 'o');
-       $reserve{'voldesc'}=$res->{'volumeddesc'};
-       $reserve{'itemtype'}=$res->{'itemtype'};
-       $reserve{'branchloop'}=\@branchloop;
-       $reserve{'optionloop'}=\@optionloop;
-       push(@reserveloop,\%reserve);
+    
+#     get borrowers reserve info
+my $reserveborrowerinfo = getpatroninformation( \%env, $res->{'borrowernumber'}, 0);
+
+    $reserve{'date'}           = format_date( $res->{'reservedate'} );
+    $reserve{'borrowernumber'} = $res->{'borrowernumber'};
+    $reserve{'biblionumber'}   = $res->{'biblionumber'};
+    $reserve{'borrowernumber'} = $res->{'borrowernumber'};
+    $reserve{'firstname'}      = $reserveborrowerinfo->{'firstname'};
+    $reserve{'surname'}        = $reserveborrowerinfo->{'surname'};
+    $reserve{'notes'}          = $res->{'reservenotes'};
+    $reserve{'wait'}           =
+      ( ( $res->{'found'} eq 'W' ) or ( $res->{'priority'} eq '0' ) );
+    $reserve{'constrainttypea'} = ( $res->{'constrainttype'} eq 'a' );
+    $reserve{'constrainttypeo'} = ( $res->{'constrainttype'} eq 'o' );
+    $reserve{'voldesc'}         = $res->{'volumeddesc'};
+    $reserve{'ccode'}           = $res->{'ccode'};
+    $reserve{'barcode'}         = $res->{'barcode'};
+    $reserve{'priority'}       = $res->{'priority'};
+    $reserve{'branchloop'} = \@branchloop;
+    $reserve{'optionloop'} = \@optionloop;
+
+    push( @reserveloop, \%reserve );
 }
 
-my @branches;
-my @select_branch;
-my %select_branches;
-my $branches=GetBranches;
-#my $count2=scalar(@branches);
-foreach my $br (keys %$branches) {
+my $default = C4::Context->userenv->{branch};
+my @values;
+my %label_of;
 
-       push @select_branch, $br;
-       $select_branches{$br}= $branches->{$br}->{'branchname'};
+foreach my $branchcode ( keys %{$branches} ) {
+    push @values, $branchcode;
+    $label_of{$branchcode} = $branches->{$branchcode}->{branchname};
 }
-my $CGIbranch=CGI::scrolling_list( -name     => 'pickup',
-                       -values   => \@select_branch,
-                       -labels   => \%select_branches,
-                       -size     => 1,
-                       -multiple => 0 );
+my $CGIbranch = CGI::scrolling_list(
+    -name     => 'pickup',
+    -values   => \@values,
+    -default  => $default,
+    -labels   => \%label_of,
+    -size     => 1,
+    -multiple => 0,
+);
 
-#get the time for the form name...
+# get the time for the form name...
 my $time = time();
 
-#setup colours
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "reserve/request.tmpl",
-                                                       query => $input,
-                            type => "intranet",
-                            authnotrequired => 0,
-                            flagsrequired => {borrowers => 1},
-                         });
-$template->param(      optionloop =>\@optionloop,
-                                                               CGIbranch => $CGIbranch,
-                                                               reserveloop => \@reserveloop,
-                                                               'time' => $time,
-                                                               bibitemloop => \@bibitemloop,
-                                                               date => $date,
-                                                               biblionumber => $biblionumber,
-                                                               title =>$dat->{title});
+$template->param(
+    CGIbranch   => $CGIbranch,
+    reserveloop => \@reserveloop,
+    time        => $time,
+    fixedRank  => $fixedRank,
+);
+
+# display infos
+$template->param(
+    optionloop        => \@optionloop,
+    bibitemloop       => \@bibitemloop,
+    date              => $date,
+    biblionumber      => $biblionumber,
+    findborrower      => $findborrower,
+    cardnumber        => $cardnumber,
+    CGIselectborrower => $CGIselectborrower,
+    title             => $dat->{title},
+    author            => $dat->{author}
+);
+
 # printout the page
-output_html_with_http_headers $input, $cookie, $template->output;
\ No newline at end of file
+output_html_with_http_headers $input, $cookie, $template->output;
index 5c0e93a..6bd4780 100644 (file)
     <items>
       <rdf:Seq>
          <!-- TMPL_LOOP NAME="ITEMS" -->
-        <rdf:li resource="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" -->"/>
+        <rdf:li resource="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->"/>
         <!-- /TMPL_LOOP -->
       </rdf:Seq>
     </items>
 </channel>
 
   <!-- TMPL_LOOP NAME="ITEMS" -->
-  <item rdf:about="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">
+  <item rdf:about="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">
   <title><!-- TMPL_VAR NAME="TITLE" --><!-- TMPL_IF NAME="AUTHOR" --> by <!-- TMPL_VAR AUTHOR --><!-- /TMPL_IF --></title>
-  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" --></link>
+  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" --></link>
 <description><![CDATA[<!-- TMPL_VAR NAME="TITLE" --><!-- TMPL_IF NAME="AUTHOR" --> by <!-- TMPL_VAR NAME="AUTHOR" --><!-- /TMPL_IF -->
 <br><!-- TMPL_VAR NAME="place" --> <!-- TMPL_VAR NAME="publishercode" --> <!-- TMPL_VAR NAME="publicationyear" -->
 <br><!-- TMPL_VAR NAME="pages" --><!-- TMPL_VAR NAME="illus" --><!-- TMPL_VAR NAME="size" -->
 <!-- TMPL_IF NAME="notes" --><br><br><!-- TMPL_VAR NAME="notes" --><!-- /TMPL_IF --><br>
-<a href="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">View Details</a> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-reserve.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">Reserve this Item</a><!-- TMPL_IF NAME="author" --> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-search.pl?marclist=biblio.author&amp;and_or=and&amp;excluding=&amp;operator=contains&amp;value=<!-- TMPL_VAR NAME="author" -->&amp;resultsperpage=20&amp;orderby=biblio.title&amp;op=do_search">More by this Author</a><!-- /TMPL_IF -->
+<a href="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">View Details</a> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-reserve.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">Reserve this Item</a><!-- TMPL_IF NAME="author" --> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-search.pl?marclist=biblio.author&amp;and_or=and&amp;excluding=&amp;operator=contains&amp;value=<!-- TMPL_VAR NAME="author" -->&amp;resultsperpage=20&amp;orderby=biblio.title&amp;op=do_search">More by this Author</a><!-- /TMPL_IF -->
 ]]></description>
  </item>
 <!-- /TMPL_LOOP -->
index febf26a..f90942f 100644 (file)
 <!-- TMPL_LOOP NAME="ITEMS" -->
  <item>
   <title><!-- TMPL_VAR NAME="TITLE" --><!-- TMPL_IF NAME="AUTHOR" --> by <!-- TMPL_VAR NAME="AUTHOR" --><!-- /TMPL_IF --></title>
-  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" --></link>
+  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" --></link>
 <description><![CDATA[<!-- TMPL_VAR NAME="TITLE" --><!-- TMPL_IF NAME="AUTHOR" --> by <!-- TMPL_VAR NAME="AUTHOR" --><!-- /TMPL_IF -->
 <br><!-- TMPL_IF NAME="publishercode" --><!-- TMPL_VAR NAME="place" --> <!-- TMPL_VAR NAME="publishercode" --> <!-- TMPL_VAR NAME="publicationyear" --><br><!-- /TMPL_IF -->
 <!-- TMPL_IF NAME="pages" --><!-- TMPL_VAR NAME="pages" --><!-- TMPL_VAR NAME="illus" --><!-- TMPL_VAR NAME="size" --><!-- /TMPL_IF -->
 <!-- TMPL_IF NAME="notes" --><p><!-- TMPL_VAR NAME="notes" --></p><!-- /TMPL_IF --><br>
-<a href="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">View Details</a> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-reserve.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">Reserve this Item</a><!-- TMPL_IF NAME="author" --> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-search.pl?marclist=biblio.author&amp;and_or=and&amp;excluding=&amp;operator=contains&amp;value=<!-- TMPL_VAR NAME="author" -->&amp;resultsperpage=20&amp;orderby=biblio.title&amp;op=do_search">More by this Author</a><!-- /TMPL_IF -->
+<a href="http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">View Details</a> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-reserve.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">Reserve this Item</a><!-- TMPL_IF NAME="author" --> | <a href="http://opac.library.org.nz/cgi-bin/koha/opac-search.pl?marclist=biblio.author&amp;and_or=and&amp;excluding=&amp;operator=contains&amp;value=<!-- TMPL_VAR NAME="author" -->&amp;resultsperpage=20&amp;orderby=biblio.title&amp;op=do_search">More by this Author</a><!-- /TMPL_IF -->
 ]]></description>
  </item>
 <!-- /TMPL_LOOP -->
index 3d4926c..b47cd18 100644 (file)
@@ -21,7 +21,7 @@
 <TMPL_LOOP NAME=ITEMS>
  <item>
   <title><TMPL_VAR TITLE>, by <TMPL_VAR AUTHOR></title>
-  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?bib=<TMPL_VAR NAME="bibid"></link>
+  <link>http://opac.library.org.nz/cgi-bin/koha/opac-detail.pl?biblionumber=<TMPL_VAR NAME="biblionumber"></link>
 
  </item>
 </TMPL_LOOP>
index edf8bd6..e6fcb6f 100755 (executable)
@@ -24,9 +24,9 @@
         <category><!-- TMPL_VAR NAME="itemtype" --></category>
         <description><![CDATA[Call Number: <!-- TMPL_VAR NAME="callno" --><br />
         <!-- TMPL_IF NAME="notes" -->Notes: <!-- TMPL_VAR NAME="notes" --><br /><!-- /TMPL_IF -->
-<a href="https://libcat.nbbc.edu/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">View Details</a> <!-- TMPL_IF NAME="reservable" -->| <a href="https://libcat.nbbc.edu/cgi-bin/koha/opac-reserve.pl?bib=<!-- TMPL_VAR NAME="bibid" -->">Reserve this Item</a><!-- /TMPL_IF -->]]>
+<a href="https://libcat.nbbc.edu/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">View Details</a> <!-- TMPL_IF NAME="reservable" -->| <a href="https://libcat.nbbc.edu/cgi-bin/koha/opac-reserve.pl?biblionumber=<!-- TMPL_VAR NAME="biblionumber" -->">Reserve this Item</a><!-- /TMPL_IF -->]]>
 </description>
-  <link>https://libcat.nbbc.edu/cgi-bin/koha/opac-detail.pl?bib=<!-- TMPL_VAR name="bibid" --></link>
+  <link>https://libcat.nbbc.edu/cgi-bin/koha/opac-detail.pl?biblionumber=<!-- TMPL_VAR name="biblionumber" --></link>
 
  </item>
 <!-- /TMPL_LOOP -->
index e936ea5..64fc617 100755 (executable)
@@ -43,12 +43,14 @@ acqui-search-result.pl
 use strict;
 use C4::Auth;
 use C4::Biblio;
+use C4::Output;
 use CGI;
 use C4::Interface::CGI::Output;
+
+
 use C4::Acquisition;
 use C4::Date;
 use C4::Bookseller;
-use C4::Acquisition;
 
 my $query=new CGI;
 my ($template, $loggedinuser, $cookie)
@@ -56,7 +58,7 @@ my ($template, $loggedinuser, $cookie)
                  query => $query,
                  type => "intranet",
                  authnotrequired => 0,
-                 flagsrequired => {acquisition => 1},
+                 flagsrequired => {serials => 1},
                  debug => 1,
                  });
 
index fcd48a7..f82dc43 100755 (executable)
@@ -24,74 +24,74 @@ use CGI;
 use C4::Auth;
 use C4::Output;
 use C4::Interface::CGI::Output;
-
 use C4::Bookfund;
-use C4::Acquisition;
-my $query = new CGI;
-
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "serials/acqui-search.tmpl",
-                            query => $query,
-                            type => "intranet",
-                            authnotrequired => 0,
-                            flagsrequired => {acquisition => 1},
-                            debug => 1,
-                            });
-
 
+my $query = new CGI;
 
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "serials/acqui-search.tmpl",
+        query           => $query,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { serials => 1 },
+        debug           => 1,
+    }
+);
 
 # budget
-my $dbh = C4::Context->dbh;
-my $sthtemp = $dbh->prepare("Select flags, branchcode from borrowers where borrowernumber = ?");
+my $dbh     = C4::Context->dbh;
+my $sthtemp =
+  $dbh->prepare(
+    "Select flags, branchcode from borrowers where borrowernumber = ?");
 $sthtemp->execute($loggedinuser);
-my ($flags, $homebranch)=$sthtemp->fetchrow;
-my @results=GetBookFunds($homebranch);
-my $count = scalar(@results);
+my ( $flags, $homebranch ) = $sthtemp->fetchrow;
+my @results = GetBookFunds($homebranch);
+my $count   = scalar(@results);
 
-my $classlist='';
-my $total=0;
-my $totspent=0;
-my $totcomtd=0;
-my $totavail=0;
+my $classlist   = '';
+my $total       = 0;
+my $totspent    = 0;
+my $totcomtd    = 0;
+my $totavail    = 0;
 my @loop_budget = ();
-for (my $i=0;$i<$count;$i++){
-       my ($spent,$comtd)=GetBookFundBreakdown($results[$i]->{'bookfundid'});
-       my $avail=$results[$i]->{'budgetamount'}-($spent+$comtd);
-       my %line;
-       $line{bookfundname} = $results[$i]->{'bookfundname'};
-       $line{budgetamount} = $results[$i]->{'budgetamount'};
-       $line{spent} = sprintf  ("%.2f", $spent);
-       $line{comtd} = sprintf  ("%.2f",$comtd);
-       $line{avail}  = sprintf  ("%.2f",$avail);
-       push @loop_budget, \%line;
-       $total+=$results[$i]->{'budgetamount'};
-       $totspent+=$spent;
-       $totcomtd+=$comtd;
-       $totavail+=$avail;
+for ( my $i = 0 ; $i < $count ; $i++ ) {
+    my ( $spent, $comtd ) =
+      GetBookFundBreakdown( $results[$i]->{'bookfundid'} );
+    my $avail = $results[$i]->{'budgetamount'} - ( $spent + $comtd );
+    my %line;
+    $line{bookfundname} = $results[$i]->{'bookfundname'};
+    $line{budgetamount} = $results[$i]->{'budgetamount'};
+    $line{spent}        = sprintf( "%.2f", $spent );
+    $line{comtd}        = sprintf( "%.2f", $comtd );
+    $line{avail}        = sprintf( "%.2f", $avail );
+    push @loop_budget, \%line;
+    $total    += $results[$i]->{'budgetamount'};
+    $totspent += $spent;
+    $totcomtd += $comtd;
+    $totavail += $avail;
 }
+
 #currencies
-my @rates=GetCurrencies();
+my @rates = GetCurrencies();
 my $count = scalar @rates;
 
 my @loop_currency = ();
-for (my $i=0;$i<$count;$i++){
-       my %line;
-       $line{currency} = $rates[$i]->{'currency'};
-       $line{rate} = $rates[$i]->{'rate'};
-       push @loop_currency, \%line;
+for ( my $i = 0 ; $i < $count ; $i++ ) {
+    my %line;
+    $line{currency} = $rates[$i]->{'currency'};
+    $line{rate}     = $rates[$i]->{'rate'};
+    push @loop_currency, \%line;
 }
-$template->param(classlist => $classlist,
-                                               type => 'intranet',
-                                               loop_budget => \@loop_budget,
-                                               loop_currency => \@loop_currency,
-                                               total => sprintf("%.2f",$total),
-                                               totspent => sprintf("%.2f",$totspent),
-                                               totcomtd => sprintf("%.2f",$totcomtd),
-                                               totavail => sprintf("%.2f",$totavail),
-                                               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
-               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
-               IntranetNav => C4::Context->preference("IntranetNav"),
-                                               );
+$template->param(
+    classlist     => $classlist,
+    type          => 'intranet',
+    loop_budget   => \@loop_budget,
+    loop_currency => \@loop_currency,
+    total         => sprintf( "%.2f", $total ),
+    totspent      => sprintf( "%.2f", $totspent ),
+    totcomtd      => sprintf( "%.2f", $totcomtd ),
+    totavail      => sprintf( "%.2f", $totavail )
+);
 
 output_html_with_http_headers $query, $cookie, $template->output;
index 9dbfee6..db08e23 100755 (executable)
@@ -5,47 +5,45 @@ use CGI;
 use C4::Auth;
 use C4::Serials;
 use C4::Acquisition;
-
+use C4::Output;
+use C4::Bookseller;
 use C4::Interface::CGI::Output;
 use C4::Context;
+use C4::Letters;
 
+my $input = new CGI;
 
-my $query = new CGI;
-
-my $serialid = $query->param('serialid');
-my $op = $query->param('op');
-# my $claimletter = $query->param('claimletter');
-my $supplierid = $query->param('supplierid');
+my $serialid = $input->param('serialid');
+my $op = $input->param('op');
+my $claimletter = $input->param('claimletter');
+my $supplierid = $input->param('supplierid');
+my $order = $input->param('order');
+warn "order :$order";
 my %supplierlist = GetSuppliersWithLateIssues;
 my @select_supplier;
 
 foreach my $supplierid (keys %supplierlist){
-        my ($count, @dummy) = GetMissingIssues($supplierid);
+        my ($count, @dummy) = GetLateOrMissingIssues($supplierid,"",$order);
         my $counting = $count;
         $supplierlist{$supplierid} = $supplierlist{$supplierid}." ($counting)";
        push @select_supplier, $supplierid
 }
 
-# my @select_letter = (1,2,3,4);
-# my %letters = (1=>'Claim Form 1',2=>'Claim Form 2',3=>'Claim Form 3',4=>'Claim Form 4');
-my ($count2, @missingissues) = GetMissingIssues($supplierid,$serialid);
+my @letters = GetLetters("claimissues");
+my $letter=((scalar(@letters)>1)||($letters[0]->{name}||$letters[0]->{code}));
+my ($count2, @missingissues) = GetLateOrMissingIssues($supplierid,$serialid,$order);
 
 my $CGIsupplier=CGI::scrolling_list( -name     => 'supplierid',
                        -values   => \@select_supplier,
                        -default  => $supplierid,
                        -labels   => \%supplierlist,
                        -size     => 1,
-                       -multiple => 0 );
+                       -multiple => 0 
+            -onChange => 'onchange="submit();"');
 
-# my $CGIletter=CGI::scrolling_list( -name     => 'claimletter',
-#                      -values   => \@select_letter,
-#                      -default  => $claimletter,
-#                      -labels   => \%letters,
-#                      -size     => 1,
-#                      -multiple => 0 );
 my ($singlesupplier,@supplierinfo);
 if($supplierid){
-   ($singlesupplier,@supplierinfo)=bookseller($supplierid);
+   (@supplierinfo)=GetBookSeller($supplierid);
 } else { # set up supplierid for the claim links out of main table if all suppliers is chosen
    for(my $i=0; $i<@missingissues;$i++){
        $missingissues[$i]->{'supplierid'} = getsupplierbyserialid($missingissues[$i]->{'serialid'});
@@ -58,26 +56,37 @@ if($op eq 'preview'){
     $preview = 1;
 }
 
+if ($op eq "send_alert"){
+  my @serialnums=$input->param("serialid");
+  SendAlerts('claimissues',\@serialnums,$input->param("letter_code"));
+  my $cntupdate=UpdateClaimdateIssues(\@serialnums);
+  ### $cntupdate SHOULD be equal to scalar(@$serialnums)
+}
+
 my ($template, $loggedinuser, $cookie)
 = get_template_and_user({template_name => "serials/claims.tmpl",
-                               query => $query,
+                               query => $input,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
+                               flagsrequired => {serials => 1},
                                debug => 1,
                                });
 
+$template->param('letters'=>\@letters,'letter'=>$letter);
 $template->param(
+    order =>$order,
        CGIsupplier => $CGIsupplier,
-#      CGIletter => $CGIletter,
+    phone => $supplierinfo[0]->{phone},
+    booksellerfax => $supplierinfo[0]->{booksellerfax},
+    bookselleremail => $supplierinfo[0]->{bookselleremail},
         preview => $preview,
         missingissues => \@missingissues,
         supplierid => $supplierid,
-#       claimletter => $claimletter,
+        claimletter => $claimletter,
         singlesupplier => $singlesupplier,
         supplierloop => \@supplierinfo,
        intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
                intranetstylesheet => C4::Context->preference("intranetstylesheet"),
                IntranetNav => C4::Context->preference("IntranetNav"),
        );
-output_html_with_http_headers $query, $cookie, $template->output;
+output_html_with_http_headers $input, $cookie, $template->output;
index 5657695..eabe967 100755 (executable)
@@ -52,9 +52,8 @@ use CGI;
 use C4::Date;
 use C4::Auth;
 use C4::Context;
-
+use C4::Output;
 use C4::Interface::CGI::Output;
-use C4::Search;
 
 use C4::Serials;
 use C4::Members;
@@ -77,7 +76,7 @@ my ($template, $borrowernumber, $cookie)
                  query => $input,
                  type => "intranet",
                  authnotrequired => 0,
-                 flagsrequired => {cataloguing => 1},
+                 flagsrequired => {serials => 1},
                  debug => 1,
                  });
 
index 4cb9c44..b4d69b4 100755 (executable)
@@ -9,6 +9,7 @@ use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Context;
 
+# use Date::Manip;
 use Text::CSV_XS;
 
 
index f40f317..6571625 100755 (executable)
@@ -1,46 +1,57 @@
 #!/usr/bin/perl
 
-# Member Search.pl script used to search for members to add to a routing list
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+=head1 member-search.pl
+
+Member Search.pl script used to search for members to add to a routing list
+=cut
+
 use strict;
 use CGI;
-use C4::Koha;
-use C4::Auth;
-use C4::Date;
-use C4::Acquisition;
+use C4::Auth;       # get_template_and_user
 use C4::Interface::CGI::Output;
-use C4::Context;
-use C4::Search;
-use C4::Serials;
+use C4::Members;    # BornameSearch
 
-my $query = new CGI;
+my $query          = new CGI;
 my $subscriptionid = $query->param('subscriptionid');
-my $op = $query->param('op');
-my $searchstring = $query->param('member');
-my $dbh = C4::Context->dbh;
-
-my $env;    
-    
-    my ($template, $loggedinuser, $cookie)
-= get_template_and_user({template_name => "serials/member-search.tmpl",
-                               query => $query,
-                               type => "intranet",
-                               authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
-                               debug => 1,
-                               });
-
-
-if($searchstring){
-    my ($count, $members) = &BornameSearch($env, $searchstring, "surname", "advanced");
-    
-    $template->param(
-       subscriptionid => $subscriptionid,
-           memberloop => $members,
-               member => $searchstring,
-    );
-} else {
+my $searchstring   = $query->param('member');
+
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "serials/member-search.tmpl",
+        query           => $query,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { serials => 1 },
+        debug           => 1,
+    }
+);
+
+if ($searchstring) {
+    my ( $count, $members ) = &BornameSearch( '', $searchstring, "surname" );
+
     $template->param(
-       subscriptionid => $subscriptionid,
+        subscriptionid => $subscriptionid,
+        memberloop     => $members,
+        member         => $searchstring,
     );
 }
-        output_html_with_http_headers $query, $cookie, $template->output;
+else {
+    $template->param( subscriptionid => $subscriptionid, );
+}
+output_html_with_http_headers $query, $cookie, $template->output;
index 0876ff4..e4eef5f 100755 (executable)
@@ -6,13 +6,15 @@
 # printed out
 use strict;
 use CGI;
-
+use C4::Koha;
+use C4::Auth;
+use C4::Date;
+use C4::Output;
 use C4::Acquisition;
 use C4::Interface::CGI::Output;
-
+use C4::Context;
 use C4::Serials;
 
-
 my $query = new CGI;
 my $subscriptionid = $query->param('subscriptionid');
 my $routingid = $query->param('routingid');
index 10d1390..53fae02 100755 (executable)
@@ -14,7 +14,8 @@ use C4::Reserves2;
 use C4::Circulation::Circ2;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use C4::Search;
+use C4::Members;
+use C4::Biblio;
 use C4::Serials;
 
 my $query = new CGI;
@@ -55,8 +56,8 @@ if($ok){
            $count--;
         }
     }
-    my ($count2,@bibitems) = bibitems($biblio);
-    my @itemresults = ItemInfo($env, $subs->{'biblionumber'}, 'intra');    
+    my ($count2,@bibitems) = GetBiblioItemByBiblioNumber($biblio);
+    my @itemresults = GetItemsInfo($subs->{'biblionumber'}, 'intra');
     my $branch = $itemresults[0]->{'holdingbranch'};
     my $const = 'o';
     my $notes;
@@ -66,12 +67,12 @@ if($ok){
                                  AND cancellationdate is NULL AND (found <> 'F' or found is NULL)");
         $sth->execute($biblio,$routinglist[$i]->{'borrowernumber'});
         my $data = $sth->fetchrow_hashref;
-#      warn Dumper($data);
+
 #       warn "$routinglist[$i]->{'borrowernumber'} is the same as $data->{'borrowernumber'}";
        if($routinglist[$i]->{'borrowernumber'} == $data->{'borrowernumber'}){
            UpdateReserve($routinglist[$i]->{'ranking'},$biblio,$routinglist[$i]->{'borrowernumber'},$branch);
         } else {
-            CreateReserve(\$env,$branch,$routinglist[$i]->{'borrowernumber'},$biblio,$const,\@bibitems,$routinglist[$i]->{'ranking'},$notes,$title);
+        CreateReserve(\$env,$branch,$routinglist[$i]->{'borrowernumber'},$biblio,$const,\@bibitems,$routinglist[$i]->{'ranking'},$notes,$title);
        }
     }
     
@@ -81,16 +82,17 @@ if($ok){
                                query => $query,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
+                               flagsrequired => {serials => 1},
                                debug => 1,
-                               });    
+                               });
+    $template->param("libraryname"=>C4::Context->preference("LibraryName"));
 } else {
     ($template, $loggedinuser, $cookie)
 = get_template_and_user({template_name => "serials/routing-preview.tmpl",
                                query => $query,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
+                               flagsrequired => {serials => 1},
                                debug => 1,
                                });
 }    
index 87a04dc..37842d8 100755 (executable)
@@ -1,25 +1,48 @@
 #!/usr/bin/perl
 
-# Routing.pl script used to create a routing list for a serial subscription
-# In this instance it is in fact a setting up of a list of reserves for the item
-# where the hierarchical order can be changed on the fly and a routing list can be
-# printed out
+# This file is part of Koha
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+
+=head1 Routing.pl
+
+script used to create a routing list for a serial subscription
+In this instance it is in fact a setting up of a list of reserves for the item
+where the hierarchical order can be changed on the fly and a routing list can be
+printed out
+
+=cut
+
 use strict;
 use CGI;
 use C4::Koha;
 use C4::Auth;
 use C4::Date;
+use C4::Output;
 use C4::Acquisition;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use C4::Search;
+
+use C4::Members;
 use C4::Serials;
 
 my $query = new CGI;
 my $subscriptionid = $query->param('subscriptionid');
 my $serialseq = $query->param('serialseq');
 my $routingid = $query->param('routingid');
-my $bornum = $query->param('bornum');
+my $borrowernumber = $query->param('borrowernumber');
 my $notes = $query->param('notes');
 my $op = $query->param('op');
 my $date_selected = $query->param('date_selected');
@@ -30,7 +53,7 @@ if($op eq 'delete'){
 }
 
 if($op eq 'add'){
-    addroutingmember($bornum,$subscriptionid);
+    addroutingmember($borrowernumber,$subscriptionid);
 }
 if($op eq 'save'){
     my $sth = $dbh->prepare("UPDATE serial SET routingnotes = ? WHERE subscriptionid = ?");
@@ -40,7 +63,7 @@ if($op eq 'save'){
     
 my ($routing, @routinglist) = getroutinglist($subscriptionid);
 my $subs = GetSubscription($subscriptionid);
-my ($count,@serials) = old_getserials($subscriptionid);
+my ($count,@serials) = GetSerials($subscriptionid);
 my ($serialdates) = GetLatestSerials($subscriptionid,$count);
 
 my @dates;
@@ -62,7 +85,7 @@ my ($template, $loggedinuser, $cookie)
                                query => $query,
                                type => "intranet",
                                authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
+                               flagsrequired => {serials => 1},
                                debug => 1,
                                });
 # my $date;
@@ -100,7 +123,7 @@ for(my $i=0;$i<$routing;$i++){
     
     push(@results, $data);
 }
-# warn Dumper(@results);
+
 # for adding routing list
 my $new;
 if ($op eq 'new') {
index f7a8603..b927789 100755 (executable)
@@ -73,7 +73,8 @@ if ($selectview eq "full"){
      = get_template_and_user({template_name => "serials/serial-issues-full.tmpl",
      query => $query,
      type => "intranet",
-     authnotrequired => 1,
+     authnotrequired => 0,
+        flagsrequired => {serials => 1},
      debug => 1,
      });
  
@@ -110,8 +111,4 @@ if ($selectview eq "full"){
         virtualshelves => "".C4::Context->preference("virtualshelves"),
     );
 }
-$template->param(intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
-               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
-               IntranetNav => C4::Context->preference("IntranetNav"),
-               );
 output_html_with_http_headers $query, $cookie, $template->output;
index 0585ed7..03b89fb 100755 (executable)
@@ -41,50 +41,51 @@ this script is the main page for serials/
 
 =cut
 
-
 use strict;
 use CGI;
 use C4::Auth;
 use C4::Serials;
+use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Context;
 
-my $query = new CGI;
-my $title = $query->param('title');
-my $ISSN = $query->param('ISSN');
-my $supplierid = $query->param('supplierid');
-my $routing = $query->param('routing');
-my $searched = $query->param('searched');
-my $biblionumber = $query->param('biblionumber');
-my $alt_links = 0;
-if(C4::Context->preference("RoutingSerials")){
-    $alt_links = 0;
+my $query         = new CGI;
+my $title         = $query->param('title_filter');
+my $ISSN          = $query->param('ISSN_filter');
+my $routing       = $query->param('routing');
+my $searched      = $query->param('searched');
+my $biblionumber  = $query->param('biblionumber');
+
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "serials/serials-home.tmpl",
+        query           => $query,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { serials => 1 },
+        debug           => 1,
+    }
+);
+
+my @subscriptions;
+if ($searched){
+    @subscriptions = GetSubscriptions( $title, $ISSN, $biblionumber );
 }
-my @subscriptions = GetSubscriptions($title,$ISSN,$biblionumber,$supplierid);
-my ($template, $loggedinuser, $cookie)
-= get_template_and_user({template_name => "serials/serials-home.tmpl",
-                               query => $query,
-                               type => "intranet",
-                               authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
-                               debug => 1,
-                               });
 
 # to toggle between create or edit routing list options
-if($routing){ 
-    for(my $i=0;$i<@subscriptions;$i++){
-       my $checkrouting = check_routing($subscriptions[$i]->{'subscriptionid'});
-       $subscriptions[$i]->{'routingedit'} = $checkrouting;
-       # warn "check $checkrouting";
+if ($routing) {
+    for ( my $i = 0 ; $i < @subscriptions ; $i++ ) {
+        my $checkrouting =
+          check_routing( $subscriptions[$i]->{'subscriptionid'} );
+        $subscriptions[$i]->{'routingedit'} = $checkrouting;
     }
 }
 
 $template->param(
-       subscriptions => \@subscriptions,
-       title => $title,
-       ISSN => $ISSN,
-        done_searched => $searched,
-        routing => $routing,
-        alt_links => $alt_links,
-       );
+    subscriptions => \@subscriptions,
+    title_filter  => $title,
+    ISSN_filter   => $ISSN,
+    done_searched => $searched,
+    routing       => $routing,
+);
 output_html_with_http_headers $query, $cookie, $template->output;
index 69493ab..d132bdb 100755 (executable)
@@ -1,7 +1,5 @@
 #!/usr/bin/perl
 
-# Copyright 2000-2003 Katipo Communications
-#
 # This file is part of Koha.
 #
 # Koha is free software; you can redistribute it and/or modify it under the
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-# $Id$
-
-=head1 NAME
-
-subscription-add.pl
-
-=head1 DESCRIPTION
-
-this script add a subscription into the database.
-
-=head1 PARAMETERS
-
-=over 4
-
-=item op
-op use to know the operation to do on this template.
- * mod : to modify an existing subscription
- * addsubscription : to add a subscription
-
-Note that if op = mod or addsubscription there are a lot of other params.
-
-
-=back
-
-=cut
-
-
 use strict;
 use CGI;
 use C4::Koha;
 use C4::Auth;
 use C4::Date;
-use C4::Serials;
-use C4::Bookfund;
+use C4::Output;
+use C4::Acquisition;
 use C4::Interface::CGI::Output;
 use C4::Context;
+use C4::Branch; # GetBranches
+use C4::Serials;
+use Date::Manip;
 use C4::Letters;
-use C4::Members;
-use DateTime;
+
 my $query = new CGI;
 my $op = $query->param('op');
 my $dbh = C4::Context->dbh;
-my ($subscriptionid,$auser,$librarian,$cost,$aqbooksellerid, $aqbooksellername,$aqbudgetid, $bookfundid, $startdate, $periodicity,
-    $publisheddate,$dow,$irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $sublength,
-    $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
-    $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
-    $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
-    $numberingmethod, $status, $biblionumber,
-    $title, $notes, $letter,$callnumber,$hemisphere);
+my ($subscriptionid,$auser,$branchcode,$librarian,$cost,$aqbooksellerid, $aqbooksellername,$aqbudgetid, $bookfundid, $startdate, $periodicity,
+       $firstacquidate, $dow, $irregularity, $numberpattern, $numberlength, $weeklength, $monthlength, $sublength,
+       $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
+       $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
+       $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
+       $numberingmethod, $status, $biblionumber, 
+       $bibliotitle, $callnumber, $notes, $hemisphere, $letter, $manualhistory);
 
-    my @budgets;
+       my @budgets;
 my ($template, $loggedinuser, $cookie)
 = get_template_and_user({template_name => "serials/subscription-add.tmpl",
-                query => $query,
-                type => "intranet",
-                authnotrequired => 0,
-                flagsrequired => {catalogue => 1},
-                debug => 1,
-                });
+                               query => $query,
+                               type => "intranet",
+                               authnotrequired => 0,
+                               flagsrequired => {serials => 1},
+                               debug => 1,
+                               });
+
 
 my $weekarrayjs='';
 my $count = 0;
-my $today=get_today();
- my $dateobj=DATE_obj($today);
-  my $year=$dateobj->year;
-  my $month=$dateobj->month;
-  my $day=$dateobj->day_of_month;
-my $firstday = $dateobj->day_of_year;
-my $wkno = $dateobj->week_number;
+my ($year, $month, $day) = UnixDate("today", "%Y", "%m", "%d");
+my $firstday = Date_DayOfYear($month,$day,$year);
+my $wkno = Date_WeekOfYear($month,$day,$year,1); # week starting monday
 my $weekno = $wkno;
 for(my $i=$firstday;$i<($firstday+365);$i=$i+7){
         $count = $i;
         if($wkno > 52){$year++; $wkno=1;}
         if($count>365){$count=$i-365;}    
-     my $newdate=DateTime->from_day_of_year(year=>$year,day_of_year=>$count);
-        $weekarrayjs .= "'Wk $wkno: ".format_date($newdate->ymd)."',";
+        my ($y,$m,$d) = Date_NthDayOfYear($year,$count);
+        my $output = "$y-$m-$d";
+        $weekarrayjs .= "'Wk $wkno: ".format_date($output)."',";
         $wkno++;    
 }
 chop($weekarrayjs);
@@ -103,197 +74,230 @@ my @subscription_types = (
             'issues', 'weeks', 'months'
         ); 
 my @sub_type_data;
-if ($op eq 'mod') {
+
+my $letters = GetLetters('serial');
+my @letterloop;
+foreach my $thisletter (keys %$letters) {
+    my $selected = 1 if $thisletter eq $letter;
+    my %row =(value => $thisletter,
+                selected => $selected,
+                lettername => $letters->{$thisletter},
+            );
+    push @letterloop, \%row;
+}
+$template->param(letterloop => \@letterloop);
+
+my $onlymine=C4::Context->preference('IndependantBranches') && 
+             C4::Context->userenv && 
+             C4::Context->userenv->{flags}!=1 && 
+             C4::Context->userenv->{branch};
+my $branches = GetBranches($onlymine);
+my @branchloop;
+foreach my $thisbranch (keys %$branches) {
+    my $selected = 1 if $thisbranch eq C4::Context->userenv->{'branch'};
+    my %row =(value => $thisbranch,
+                selected => $selected,
+                branchname => $branches->{$thisbranch}->{'branchname'},
+            );
+    push @branchloop, \%row;
+}
+$template->param(branchloop => \@branchloop);
+
+if ($op eq 'mod'||$op eq 'dup') {
     my $subscriptionid = $query->param('subscriptionid');
+#     warn "irregularity :$irregularity numberpattern : $numberpattern, callnumber :$callnumber, firstacquidate :$firstacquidate";
     my $subs = &GetSubscription($subscriptionid);
-    $auser = $subs->{'user'};
-    $librarian = $subs->{'librarian'};
-    $cost = $subs->{'cost'};
-    $aqbooksellerid = $subs->{'aqbooksellerid'};
-    $aqbooksellername = $subs->{'aqbooksellername'};
-    $bookfundid = $subs->{'bookfundid'};
-    $aqbudgetid = $subs->{'aqbudgetid'};
-    defined $aqbudgetid or $aqbudgetid='';
-    $startdate = $subs->{'startdate'};
-   $publisheddate = $subs->{'publisheddate'};
-    $periodicity = $subs->{'periodicity'};
-    $dow = $subs->{'dow'};
-        $irregularity = $subs->{'irregularity'};
-        $numberpattern = $subs->{'numberpattern'};
-    $numberlength = $subs->{'numberlength'};
-    $weeklength = $subs->{'weeklength'};
-    $monthlength = $subs->{'monthlength'};
-       if($monthlength > 0){
-           $sublength = $monthlength;
-           $sub_on = $subscription_types[2];
-       } elsif ($weeklength>0){
-           $sublength = $weeklength;
-           $sub_on = $subscription_types[1];
-       } else {
-           $sublength = $numberlength;
-           $sub_on = $subscription_types[0];
-       }
-        
+    $subs->{'startdate'}=format_date($subs->{'startdate'});
+    $subs->{'firstacquidate'}=format_date($subs->{'firstacquidate'});
+    $subs->{'histstartdate'}=format_date($subs->{'histstartdate'});
+    $subs->{'enddate'}=format_date($subs->{enddate});
+    $subs->{'letter'}='' unless($subs->{'letter'});
 
-        while (@subscription_types) {
-           my $sub_type = shift @subscription_types;
-           my %row = ( 'name' => $sub_type );
-           if ( $sub_on eq $sub_type ) {
-            $row{'selected'} = ' selected';
-           } else {
-            $row{'selected'} = '';
-           }
-           push( @sub_type_data, \%row );
+    if($subs->{numberlength} > 0){
+        $sublength = $subs->{numberlength};
+        $sub_on = $subscription_types[0];
+    } elsif ($subs->{weeklength}>0){
+        $sublength = $weeklength;
+        $sub_on = $subscription_types[1];
+    } else {
+        $sublength = $subs->{monthlength};
+        $sub_on = $subscription_types[2];
+    }
+    while (@subscription_types) {
+        my $sub_type = shift @subscription_types;
+        my %row = ( 'name' => $sub_type );
+        if ( $sub_on eq $sub_type ) {
+            $row{'selected'} = ' selected';
+        } else {
+            $row{'selected'} = '';
         }
-    $add1 = $subs->{'add1'};
-    $every1 = $subs->{'every1'};
-    $whenmorethan1 = $subs->{'whenmorethan1'};
-    $setto1 = $subs->{'setto1'};
-    $lastvalue1 = $subs->{'lastvalue1'};
-    $innerloop1 = $subs->{'innerloop1'};
-    $add2 = $subs->{'add2'};
-    $every2 = $subs->{'every2'};
-    $whenmorethan2 = $subs->{'whenmorethan2'};
-    $setto2 = $subs->{'setto2'};
-    $lastvalue2 = $subs->{'lastvalue2'};
-    $innerloop2 = $subs->{'innerloop2'};
-    $add3 = $subs->{'add3'};
-    $every3 = $subs->{'every3'};
-    $whenmorethan3 = $subs->{'whenmorethan3'};
-    $setto3 = $subs->{'setto3'};
-    $lastvalue3 = $subs->{'lastvalue3'};
-    $innerloop3 = $subs->{'innerloop3'};
-    $numberingmethod = $subs->{'numberingmethod'};
-    $status = $subs->{status};
-    $biblionumber = $subs->{'biblionumber'};
-    $title = $subs->{'title'},
-           $callnumber = $subs->{'callnumber'};
-           $hemisphere = $subs->{'hemisphere'};
-    $notes = $subs->{'notes'};
-    $letter = $subs->{'letter'};
-    defined $letter or $letter='';
-    $template->param(
-        $op => 1,
-        user => $auser,
-        librarian => $librarian,
-        aqbooksellerid => $aqbooksellerid,
-        aqbooksellername => $aqbooksellername,
-        cost => $cost,
-        aqbudgetid => $aqbudgetid,
-        bookfundid => $bookfundid,
-        startdate => format_date($startdate),    
-         publisheddate => format_date($publisheddate),    
-        periodicity => $periodicity,
-        numberpattern=>$numberpattern,
-        dow => $dow,
-        numberlength => $numberlength,
-        weeklength => $weeklength,
-        monthlength => $monthlength,
-       sublength=>$sublength,
-        add1 => $add1,
-        every1 => $every1,
-        whenmorethan1 => $whenmorethan1,
-        setto1 => $setto1,
-        lastvalue1 => $lastvalue1,
-        innerloop1 => $innerloop1,
-        add2 => $add2,
-        every2 => $every2,
-        whenmorethan2 => $whenmorethan2,
-        setto2 => $setto2,
-        lastvalue2 => $lastvalue2,
-        innerloop2 => $innerloop2,
-        add3 => $add3,
-        every3 => $every3,
-        whenmorethan3 => $whenmorethan3,
-        setto3 => $setto3,
-        lastvalue3 => $lastvalue3,
-        innerloop3 => $innerloop3,
-        numberingmethod => $numberingmethod,
-        status => $status,
-        biblionumber => $biblionumber,
-        title => $title,
-               callnumber => $callnumber,
-        notes => $notes,
-        letter => $letter,
-        subscriptionid => $subscriptionid,
-        weekarrayjs => $weekarrayjs,
-               weekno => $weekno,
-               hemisphere => $hemisphere,
-        "periodicity$periodicity" => 1,
-        "dow$dow" => 1,
-        "numberpattern$numberpattern" => 1,
-        );
-}
+        push( @sub_type_data, \%row );
+    }
 
-my @letterlist = GetLetterList('serial');
-for (my $i=0;$i<=$#letterlist;$i++) {
-    $letterlist[$i]->{'selected'} =1 if $letterlist[$i]->{'code'} eq $letter;
+    $template->param($subs);
+    $template->param(
+            $op => 1,
+            subtype => \@sub_type_data,
+            sublength =>$sublength,
+            history => ($op eq 'mod' && ($subs->{recievedlist}||$subs->{missinglist}||$subs->{opacnote}||$subs->{librariannote}))
+            );
+    $template->param(
+                "periodicity".$subs->{'periodicity'} => 1,
+                "dow".$subs->{'periodicity'} => 1,
+                "numberpattern".$subs->{'periodicity'} => 1,
+                );
 }
-$template->param(letters => \@letterlist);
 
 if ($op eq 'addsubscription') {
-  my @irregular = $query->param('irregular');
-        my $irregular_count = @irregular;
-        for(my $i =0;$i<$irregular_count;$i++){
-            $irregularity .=$irregular[$i]."|";
-        }
-        $irregularity =~ s/\|$//;
-        
+    my @irregular = $query->param('irregular');
+    my $irregular_count = scalar(@irregular);
+    for(my $i =0;$i<$irregular_count;$i++){
+        $irregularity .=$irregular[$i].",";
+    }
+    $irregularity =~ s/\,$//;
+
     my $auser = $query->param('user');
+    my $branchcode = $query->param('branchcode');
     my $aqbooksellerid = $query->param('aqbooksellerid');
     my $cost = $query->param('cost');
-    my $aqbudgetid = $query->param('aqbudgetid');
+    my $aqbudgetid = $query->param('aqbudgetid'); 
     my $startdate = $query->param('startdate');
-     my $publisheddate = $query->param('publisheddate');
-    my $callnumber=$query->param('callnumber');          
+    my $firstacquidate = $query->param('firstacquidate');    
     my $periodicity = $query->param('periodicity');
     my $dow = $query->param('dow');
-       my $numberlength = 0;
-       my $weeklength = 0;
-       my $monthlength = 0;
-        my $numberpattern = $query->param('numbering_pattern');
-        my $sublength = $query->param('sublength');
-        my $subtype = $query->param('subtype');
-        if ($subtype eq 'months'){
-           $monthlength = $sublength;
-       } elsif ($subtype eq 'weeks'){
-           $weeklength = $sublength;
-       } else {
-           $numberlength = $sublength;
-       }
+    my $irregularity = $query->param('irregularity');
+    my $numberlength = 0;
+    my $weeklength = 0;
+    my $monthlength = 0;
+    my $numberpattern = $query->param('numbering_pattern');
+    my $sublength = $query->param('sublength');
+    my $subtype = $query->param('subtype');
+    if ($subtype eq 'months'){
+        $monthlength = $sublength;
+    } elsif ($subtype eq 'weeks'){
+        $weeklength = $sublength;
+    } else {
+        $numberlength = $sublength;
+    }
+
+    my $add1 = $query->param('add1');
+    my $every1 = $query->param('every1');
+    my $whenmorethan1 = $query->param('whenmorethan1');
+    my $setto1 = $query->param('setto1');
+    my $lastvalue1 = $query->param('lastvalue1');
+    my $add2 = $query->param('add2');
+    my $every2 = $query->param('every2');
+    my $whenmorethan2 = $query->param('whenmorethan2');
+    my $setto2 = $query->param('setto2');
+    my $lastvalue2 = $query->param('lastvalue2');
+    my $add3 = $query->param('add3');
+    my $every3 = $query->param('every3');
+    my $whenmorethan3 = $query->param('whenmorethan3');
+    my $setto3 = $query->param('setto3');
+    my $lastvalue3 = $query->param('lastvalue3');
+    my $numberingmethod = $query->param('numberingmethod');
+    my $status = 1;
+    my $biblionumber = $query->param('biblionumber');
+    my $callnumber = $query->param('callnumber');
+    my $notes = $query->param('notes');
+    my $internalnotes = $query->param('internalnotes');
+    my $hemisphere = $query->param('hemisphere') || 1;
+       my $letter = $query->param('letter');
+    ### BugFIX : hdl doesnot know what innerloops or letter stand for but it seems necessary. So he adds them.
+    my $manualhistory = $query->param('manualhist');
+    my ($innerloop1,$innerloop2,$innerloop3);
+       my $subscriptionid = NewSubscription($auser,$branchcode,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
+                                       $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
+                                       $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
+                                       $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
+                                       $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
+                                       $numberingmethod, $status, $notes,$letter,$firstacquidate,$irregularity,
+                    $numberpattern, $callnumber, $hemisphere,($manualhistory?$manualhistory:0),$internalnotes
+                               );
 
+    print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
+} elsif ($op eq 'modsubscription') {
+    my $subscriptionid = $query->param('subscriptionid');
+    my @irregular = $query->param('irregular');
+    my $irregular_count = @irregular;
+    for(my $i =0;$i<$irregular_count;$i++){
+      $irregularity .=$irregular[$i].",";
+      warn "irregular : $irregular[$i] string :$irregularity";
+    }
+    $irregularity =~ s/\,$//;
 
-       my $add1 = $query->param('add1');
-       my $every1 = $query->param('every1');
-       my $whenmorethan1 = $query->param('whenmorethan1');
-       my $setto1 = $query->param('setto1');
-       my $lastvalue1 = $query->param('lastvalue1');
-       my $add2 = $query->param('add2');
-       my $every2 = $query->param('every2');
-       my $whenmorethan2 = $query->param('whenmorethan2');
-       my $setto2 = $query->param('setto2');
-       my $lastvalue2 = $query->param('lastvalue2');
-       my $add3 = $query->param('add3');
-       my $every3 = $query->param('every3');
-       my $whenmorethan3 = $query->param('whenmorethan3');
-       my $setto3 = $query->param('setto3');
-       my $lastvalue3 = $query->param('lastvalue3');
-       my $numberingmethod = $query->param('numberingmethod');
-       my $status = 1;
+    my $auser = $query->param('user');
+    my $librarian => $query->param('librarian'),
+    my $branchcode = $query->param('branchcode');
+    my $cost = $query->param('cost');
+    my $aqbooksellerid = $query->param('aqbooksellerid');
     my $biblionumber = $query->param('biblionumber');
+    my $aqbudgetid = $query->param('aqbudgetid');
+    my $startdate = format_date_in_iso($query->param('startdate'));
+    my $firstacquidate = format_date_in_iso($query->param('firstacquidate'));    
+    my $periodicity = $query->param('periodicity');
+    my $dow = $query->param('dow');
+    my $sublength = $query->param('sublength');
+    my $subtype = $query->param('subtype');
+
+    if($subtype eq 'months'){
+        $monthlength = $sublength;
+    } elsif ($subtype eq 'weeks'){
+        $weeklength = $sublength;
+    } else {
+        $numberlength = $sublength;
+    }
+    my $numberpattern = $query->param('numbering_pattern');
+    my $add1 = $query->param('add1');
+    my $every1 = $query->param('every1');
+    my $whenmorethan1 = $query->param('whenmorethan1');
+    my $setto1 = $query->param('setto1');
+    my $lastvalue1 = $query->param('lastvalue1');
+    my $innerloop1 = $query->param('innerloop1');
+    my $add2 = $query->param('add2');
+    my $every2 = $query->param('every2');
+    my $whenmorethan2 = $query->param('whenmorethan2');
+    my $setto2 = $query->param('setto2');
+    my $lastvalue2 = $query->param('lastvalue2');
+    my $innerloop2 = $query->param('innerloop2');
+    my $add3 = $query->param('add3');
+    my $every3 = $query->param('every3');
+    my $whenmorethan3 = $query->param('whenmorethan3');
+    my $setto3 = $query->param('setto3');
+    my $lastvalue3 = $query->param('lastvalue3');
+    my $innerloop3 = $query->param('innerloop3');
+    my $numberingmethod = $query->param('numberingmethod');
+    my $status = 1;
+    my $callnumber = $query->param('callnumber');
     my $notes = $query->param('notes');
+    my $internalnotes = $query->param('internalnotes');
+    my $hemisphere = $query->param('hemisphere');
     my $letter = $query->param('letter');
-            my $hemisphere = $query->param('hemisphere') || 1;
+    my $manualhistory = $query->param('manualhist');
+    my $enddate = $query->param('enddate');
+    my $histstartdate = format_date_in_iso($query->param('histstartdate'));
+    my $recievedlist = $query->param('recievedlist');
+    my $missinglist = $query->param('missinglist');
+    my $opacnote = $query->param('opacnote');
+    my $librariannote = $query->param('librariannote');
+    &ModSubscription(
+        $auser,           $branchcode,   $aqbooksellerid, $cost,
+        $aqbudgetid,      $startdate,    $periodicity,    $firstacquidate,
+        $dow,             $irregularity, $numberpattern,  $numberlength,
+        $weeklength,      $monthlength,  $add1,           $every1,
+        $whenmorethan1,   $setto1,       $lastvalue1,     $innerloop1,
+        $add2,            $every2,       $whenmorethan2,  $setto2,
+        $lastvalue2,      $innerloop2,   $add3,           $every3,
+        $whenmorethan3,   $setto3,       $lastvalue3,     $innerloop3,
+        $numberingmethod, $status,       $biblionumber,   $callnumber,
+        $notes,           $letter,       $hemisphere,     $manualhistory,$internalnotes,
+        $subscriptionid);
 
-    my $subscriptionid = NewSubscription($auser,$aqbooksellerid,$cost,$aqbudgetid,$biblionumber,
-                    $startdate,$periodicity,$dow,$numberlength,$weeklength,$monthlength,
-                    $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,
-                    $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,
-                    $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,
-                    $numberingmethod, $status, $notes, $letter,$irregularity,$hemisphere,$callnumber,$numberpattern,$publisheddate    );
+    ModSubscriptionHistory ($subscriptionid,$histstartdate,$enddate,$recievedlist,$missinglist,$opacnote,$librariannote);
     print $query->redirect("/cgi-bin/koha/serials/subscription-detail.pl?subscriptionid=$subscriptionid");
 } else {
-     while (@subscription_types) {
+
+        while (@subscription_types) {
            my $sub_type = shift @subscription_types;
            my %row = ( 'name' => $sub_type );
            if ( $sub_on eq $sub_type ) {
@@ -307,5 +311,5 @@ if ($op eq 'addsubscription') {
                 weekarrayjs => $weekarrayjs,
                 weekno => $weekno,
        );
-    output_html_with_http_headers $query, $cookie, $template->output;
+       output_html_with_http_headers $query, $cookie, $template->output;
 }
index 8f44929..4f2e2bf 100755 (executable)
 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 # Suite 330, Boston, MA  02111-1307 USA
 
-use strict;
 
+=head1 NAME
+
+subscription-bib-search.pl
+
+=head1 DESCRIPTION
+
+this script search among all existing subscriptions.
+
+=head1 PARAMETERS
+
+=over 4
+
+=item op
+op use to know the operation to do on this template.
+ * do_search : to search the subscription.
+
+Note that if op = do_search there are some others params specific to the search :
+    marclist,and_or,excluding,operator,value
+
+=item startfrom
+to multipage gestion.
+
+
+=back
+
+=cut
+
+
+use strict;
+require Exporter;
 use CGI;
 use C4::Koha;
 use C4::Auth;
 use C4::Context;
-use C4::Search;
-use C4::Auth;
+use C4::Output;
 use C4::Interface::CGI::Output;
+use C4::Search;
 use C4::Biblio;
-use C4::Acquisition;
-use C4::Koha; # XXX subfield_is_koha_internal_p
-
 
-# Creates a scrolling list with the associated default value.
-# Using more than one scrolling list in a CGI assigns the same default value to all the
-# scrolling lists on the page !?!? That's why this function was written.
-
-my $query=new CGI;
-my $type=$query->param('type');
-my $op = $query->param('op');
+my $input=new CGI;
+# my $type=$query->param('type');
+my $op = $input->param('op');
 my $dbh = C4::Context->dbh;
 
-my $startfrom=$query->param('startfrom');
-$startfrom=0 if(!defined $startfrom);
+my $startfrom=$input->param('startfrom');
+$startfrom=0 unless $startfrom;
 my ($template, $loggedinuser, $cookie);
 my $resultsperpage;
 
 if ($op eq "do_search") {
-       my @kohafield = $query->param('kohafield');
-       my @and_or = $query->param('and_or');
-       my @relation = $query->param('relation');
-       my @value = $query->param('value');
-       my $order=$query->param('order');
-       $resultsperpage= $query->param('resultsperpage');
-       $resultsperpage = 9 if(!defined $resultsperpage);
-       # builds tag and subfield arrays
-       
-       my ($total,$facets,@results) = ZEBRAsearch_kohafields(\@kohafield,\@value,\@relation,$order,\@and_or,1,"",$startfrom,$resultsperpage,"intranet");
-                                                                               
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "serials/result.tmpl",
-                               query => $query,
-                               type => "intranet",
-                               authnotrequired => 0,
-                               flagsrequired => {borrowers => 1},
-                               flagsrequired => {catalogue => 1},
-                               debug => 1,
-                               });
-
-       # multi page display gestion
-       my $displaynext=0;
-       my $displayprev=$startfrom;
-       if(($total - (($startfrom+1)*($resultsperpage))) > 0 ){
-               $displaynext = 1;
-       }
-
-       my @field_data = ();
-
-
-       for(my $i = 0 ; $i <= $#value ; $i++)
-       {
-               push @field_data, { term => "kohafield", val=>$kohafield[$i] };
-               push @field_data, { term => "and_or", val=>$and_or[$i] };
-               push @field_data, { term => "relation", val=>$relation[$i] };
-               push @field_data, { term => "value", val=>$value[$i] };
-       }
-
-       my @numbers = ();
-
-       if ($total>$resultsperpage)
-       {
-               for (my $i=1; $i<$total/$resultsperpage+1; $i++)
-               {
-                       if ($i<16)
-                       {
-                       my $highlight=0;
-                       ($startfrom==($i-1)) && ($highlight=1);
-                       push @numbers, { number => $i,
-                                       highlight => $highlight ,
-                                       searchdata=> \@field_data,
-                                       startfrom => ($i-1)};
-                       }
-       }
-       }
-
-       my $from = $startfrom*$resultsperpage+1;
-       my $to;
-
-       if($total < (($startfrom+1)*$resultsperpage))
-       {
-               $to = $total;
-       } else {
-               $to = (($startfrom+1)*$resultsperpage);
-       }
-       $template->param(result => \@results,
-                                                       startfrom=> $startfrom,
-                                                       displaynext=> $displaynext,
-                                                       displayprev=> $displayprev,
-                                                       resultsperpage => $resultsperpage,
-                                                       startfromnext => $startfrom+1,
-                                                       startfromprev => $startfrom-1,
-                                                       searchdata=>\@field_data,
-                                                       total=>$total,
-                                                       from=>$from,
-                                                       to=>$to,
-                                                       numbers=>\@numbers,
-                                                       );
-} else {
-       ($template, $loggedinuser, $cookie)
-               = get_template_and_user({template_name => "serials/subscription-bib-search.tmpl",
-                               query => $query,
-                               type => "intranet",
-                               authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
-                               debug => 1,
-                               });
-       my $sth=$dbh->prepare("Select itemtype,description from itemtypes order by description");
-       $sth->execute;
-       my  @itemtype;
-       my %itemtypes;
-       push @itemtype, "";
-       $itemtypes{''} = "";
-       while (my ($value,$lib) = $sth->fetchrow_array) {
-               push @itemtype, $value;
-               $itemtypes{$value}=$lib;
-       }
-
-       my $CGIitemtype=CGI::scrolling_list( -name     => 'value',
-                               -values   => \@itemtype,
-                               -labels   => \%itemtypes,
-                               -size     => 1,
-                               -tabindex=>'',
-                               -multiple => 0 );
-       $sth->finish;
-
-       $template->param(
-                       CGIitemtype => $CGIitemtype,
-                       );
+    my $query = $input->param('q');
+
+    $resultsperpage= $input->param('resultsperpage');
+    $resultsperpage = 19 if(!defined $resultsperpage);
+
+    my ($error,$marcrecords) = SimpleSearch($query);
+    my $total = scalar @$marcrecords;
+
+    if (defined $error) {
+        $template->param(query_error => $error);
+        warn "error: ".$error;
+        output_html_with_http_headers $input, $cookie, $template->output;
+        exit;
+    }
+    my @results;
+    warn "total=".$total;
+    
+    for(my $i=0;$i<$total;$i++) {
+        my %resultsloop;
+        my $marcrecord = MARC::File::USMARC::decode($marcrecords->[$i]);
+        my $biblio = MARCmarc2koha(C4::Context->dbh,$marcrecord,'');
+
+        #build the hash for the template.
+        $resultsloop{highlight}       = ($i % 2)?(1):(0);
+        $resultsloop{title}           = $biblio->{'title'};
+        $resultsloop{subtitle}        = $biblio->{'subtitle'};
+        $resultsloop{biblionumber}    = $biblio->{'biblionumber'};
+        $resultsloop{author}          = $biblio->{'author'};
+        $resultsloop{publishercode}   = $biblio->{'publishercode'};
+        $resultsloop{publicationyear} = $biblio->{'publicationyear'};
+
+        push @results, \%resultsloop;
+    }
+    
+    ($template, $loggedinuser, $cookie)
+        = get_template_and_user({template_name => "serials/result.tmpl",
+                query => $input,
+                type => "intranet",
+                authnotrequired => 0,
+                flagsrequired => {serials => 1},
+                flagsrequired => {catalogue => 1},
+                debug => 1,
+                });
+
+    # multi page display gestion
+    my $displaynext=0;
+    my $displayprev=$startfrom;
+    if(($total - (($startfrom+1)*($resultsperpage))) > 0 ){
+        $displaynext = 1;
+    }
+
+
+    my @numbers = ();
+
+    if ($total>$resultsperpage)
+    {
+        for (my $i=1; $i<$total/$resultsperpage+1; $i++)
+        {
+            if ($i<16)
+            {
+                my $highlight=0;
+                ($startfrom==($i-1)) && ($highlight=1);
+                push @numbers, { number => $i,
+                    highlight => $highlight ,
+                    searchdata=> \@results,
+                    startfrom => ($i-1)};
+            }
+        }
+    }
+
+    my $from = $startfrom*$resultsperpage+1;
+    my $to;
+
+    if($total < (($startfrom+1)*$resultsperpage))
+    {
+        $to = $total;
+    } else {
+        $to = (($startfrom+1)*$resultsperpage);
+    }
+    $template->param(
+                            query => $query,
+                            resultsloop => \@results,
+                            startfrom=> $startfrom,
+                            displaynext=> $displaynext,
+                            displayprev=> $displayprev,
+                            resultsperpage => $resultsperpage,
+                            startfromnext => $startfrom+1,
+                            startfromprev => $startfrom-1,
+                            total=>$total,
+                            from=>$from,
+                            to=>$to,
+                            numbers=>\@numbers,
+                            );
+} # end of if ($op eq "do_search")
+ else {
+    ($template, $loggedinuser, $cookie)
+        = get_template_and_user({template_name => "serials/subscription-bib-search.tmpl",
+                query => $input,
+                type => "intranet",
+                authnotrequired => 0,
+                flagsrequired => {catalogue => 1, serials=>1},
+                debug => 1,
+                });
+
+    my  %itemtypes = GetItemTypes();
+    my @values = values %itemtypes;
+    my $CGIitemtype=CGI::scrolling_list(
+            -name     => 'value',
+            -values   => \@values,
+            -labels   => \%itemtypes,
+            -size     => 1,
+            -multiple => 0
+    );
+
+    $template->param(
+            CGIitemtype => $CGIitemtype,
+    );
 }
 
-
 # Print the page
-$template->param(intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
-               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
-               IntranetNav => C4::Context->preference("IntranetNav"),
-               );
-output_html_with_http_headers $query, $cookie, $template->output;
+output_html_with_http_headers $input, $cookie, $template->output;
 
 # Local Variables:
 # tab-width: 4
index e1bc6e3..a416d69 100755 (executable)
@@ -10,7 +10,7 @@ use C4::Output;
 use C4::Acquisition;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use HTML::Template;
+
 use C4::Serials;
 use Date::Manip;
 
index 9cd2948..5f7c88e 100755 (executable)
@@ -1,5 +1,20 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 use CGI;
 use C4::Auth;
@@ -9,7 +24,7 @@ use C4::Serials;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Context;
-use DateTime;
+use Date::Manip;
 
 my $query = new CGI;
 my $op = $query->param('op');
@@ -18,20 +33,19 @@ my $sth;
 # my $id;
 my ($template, $loggedinuser, $cookie, $subs);
 my ($subscriptionid,$auser,$librarian,$cost,$aqbooksellerid, $aqbooksellername,$aqbudgetid, $bookfundid, $startdate, $periodicity,
-       $publisheddate, $dow, $irregularity, $sublength, $subtype, $numberpattern, $numberlength, $weeklength, $monthlength,
-       $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
-       $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
-       $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
-       $numberingmethod, $status, $biblionumber, $bibliotitle, $callnumber, $notes, $hemisphere);
+    $firstacquidate, $dow, $irregularity, $sublength, $subtype, $numberpattern, $numberlength, $weeklength, $monthlength,
+    $add1,$every1,$whenmorethan1,$setto1,$lastvalue1,$innerloop1,
+    $add2,$every2,$whenmorethan2,$setto2,$lastvalue2,$innerloop2,
+    $add3,$every3,$whenmorethan3,$setto3,$lastvalue3,$innerloop3,
+    $numberingmethod, $status, $biblionumber, $bibliotitle, $callnumber, $notes, $hemisphere,$letter,$manualhistory,$histstartdate,$enddate,$missinglist,$recievedlist,$opacnote,$librariannote);
 
 $subscriptionid = $query->param('subscriptionid');
 
 
 if ($op eq 'del') {
-$biblionumber = $query->param('biblionumber');
-       &DelSubscription($subscriptionid,$biblionumber);
-       $query->redirect("/cgi-bin/koha/serials/serials-home.pl");
-       exit;
+    &DelSubscription($subscriptionid);
+    print "Content-Type: text/html\n\n<META HTTP-EQUIV=Refresh CONTENT=\"0; URL=serials-home.pl\"></html>";
+    exit;
 
 }
 my $subs = &GetSubscription($subscriptionid);
@@ -42,90 +56,54 @@ $totalissues-- if $totalissues; # the -1 is to have 0 if this is a new subscript
 
 ($template, $loggedinuser, $cookie)
 = get_template_and_user({template_name => "serials/subscription-detail.tmpl",
-                               query => $query,
-                               type => "intranet",
-                               authnotrequired => 0,
-                               flagsrequired => {catalogue => 1},
-                               debug => 1,
-                               });
+                query => $query,
+                type => "intranet",
+                authnotrequired => 0,
+                flagsrequired => {serials => 1},
+                debug => 1,
+                });
 
 my ($user, $cookie, $sessionID, $flags)
-       = checkauth($query, 0, {catalogue => 1}, "intranet");
+    = checkauth($query, 0, {catalogue => 1}, "intranet");
 
 my $weekarrayjs='';
 my $count = 0;
-my $today=get_today();
- my $dateobj=DATE_obj($today);
-  my $year=$dateobj->year;
-  my $month=$dateobj->month;
-  my $day=$dateobj->day_of_month;
-my $firstday = $dateobj->day_of_year;
-my $wkno = $dateobj->week_number;
+my ($year, $month, $day) = UnixDate("today", "%Y", "%m", "%d");
+my $firstday = Date_DayOfYear($month,$day,$year);
+my $wkno = Date_WeekOfYear($month,$day,$year,1); # week starting monday
 my $weekno = $wkno;
 for(my $i=$firstday;$i<($firstday+365);$i=$i+7){
-        $count = $i;
-        if($wkno > 52){$year++; $wkno=1;}
-        if($count>365){$count=$i-365;}    
-     my $newdate=DateTime->from_day_of_year(year=>$year,day_of_year=>$count);
-        $weekarrayjs .= "'Wk $wkno: ".format_date($newdate->ymd)."',";
-        $wkno++;    
-}
+            $count = $i;
+            if($wkno > 52){$year++; $wkno=1;}
+            if($count>365){$count=$i-365;}
+            my ($y,$m,$d) = Date_NthDayOfYear($year,$count);
+            my $output = "$y-$m-$d";
+            $weekarrayjs .= "'Wk $wkno: ".format_date($output)."',";
+            $wkno++;
+    }
 chop($weekarrayjs);
 
+# COMMENT hdl : IMHO, we should think about passing more and more data hash to template->param rather than duplicating code a new coding Guideline ?
+$subs->{startdate}=format_date($subs->{startdate});
+$subs->{firstacquidate}=format_date($subs->{firstacquidate});
+$subs->{histstartdate}=format_date($subs->{histstartdate});
+$subs->{enddate}=format_date($subs->{enddate});
+$subs->{abouttoexpire}=abouttoexpire($subs->{subscriptionid});
+
+$template->param($subs);
+
 $template->param(
-        routing => $routing,
-       user => $subs->{auser},
-       librarian => $subs->{librarian},
-       aqbooksellerid => $subs->{aqbooksellerid},
-       aqbooksellername => $subs->{aqbooksellername},
-       cost => $subs->{cost},
-       aqbudgetid => $subs->{aqbudgetid},
-       bookfundid => $subs->{bookfundid},
-       startdate => format_date($subs->{startdate}),
-       publisheddate => format_date($subs->{publisheddate}),    
-       periodicity => $subs->{periodicity},
-       dow => $subs->{dow},
-        irregularity => $subs->{irregularity},
-       numberlength => $subs->{numberlength},
-       weeklength => $subs->{weeklength},
-       monthlength => $subs->{monthlength},
-        numberpattern => $subs->{numberpattern},
-       add1 => $subs->{add1},
-       every1 => $subs->{every1},
-       whenmorethan1 => $subs->{whenmorethan1},
-       innerloop1 => $subs->{innerloop1},
-       setto1 => $subs->{setto1},
-       lastvalue1 => $subs->{lastvalue1},
-       add2 => $subs->{add2},
-       every2 => $subs->{every2},
-       whenmorethan2 => $subs->{whenmorethan2},
-       setto2 => $subs->{setto2},
-       lastvalue2 => $subs->{lastvalue2},
-       innerloop2 => $subs->{innerloop2},
-       add3 => $subs->{add3},
-       every3 => $subs->{every3},
-       whenmorethan3 => $subs->{whenmorethan3},
-       setto3 => $subs->{setto3},
-       lastvalue3 => $subs->{lastvalue3},
-       innerloop3 => $subs->{innerloop3},
-        weekarrayjs => $weekarrayjs,
-       numberingmethod => $subs->{numberingmethod},
-       status => $subs->{status},
-       biblionumber => $subs->{biblionumber},
-       bibliotitle => $subs->{bibliotitle},
-        callnumber => $subs->{callnumber},
-       notes => $subs->{notes},
-       subscriptionid => $subs->{subscriptionid},
-       serialslist => \@serialslist,
-       totalissues => $totalissues,
-        hemisphere => $hemisphere,
-       );
+    routing => $routing,
+    serialslist => \@serialslist,
+    totalissues => $totalissues,
+    hemisphere => $hemisphere,
+    );
 $template->param(
-                       "periodicity$subs->{periodicity}" => 1,
-                       "arrival$subs->{dow}" => 1,
-                        "numberpattern$subs->{numberpattern}" => 1,
-                       intranetstylesheet => C4::Context->preference("intranetstylesheet"),
-                       intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"), 
-                       );
+            "periodicity".$subs->{periodicity} => 1,
+            "arrival".$subs->{dow} => 1,
+            "numberpattern".$subs->{numberpattern} => 1,
+            intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+            intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"), 
+            );
 
 output_html_with_http_headers $query, $cookie, $template->output;
index b5ef08f..16cdc7e 100755 (executable)
@@ -52,9 +52,10 @@ use CGI;
 use C4::Koha;
 use C4::Auth;
 use C4::Date;
+
 use C4::Context;
-use C4::Search;
 use C4::Auth;
+use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::Serials;
 
@@ -69,7 +70,7 @@ my ($template, $loggedinuser, $cookie)
                 query => $query,
                 type => "intranet",
                 authnotrequired => 0,
-                flagsrequired => {catalogue => 1},
+                flagsrequired => {serials => 1},
                 debug => 1,
                 });
 if ($op eq "renew") {
@@ -79,7 +80,7 @@ if ($op eq "renew") {
 
 my $subscription= GetSubscription($subscriptionid);
 
-$template->param(startdate => format_date(GetSubscriptionExpirationDate($subscriptionid)),
+$template->param(startdate => format_date(GetExpirationDate($subscriptionid)),
                 numberlength => $subscription->{numberlength},
                 weeklength => $subscription->{weeklength},
                 monthlength => $subscription->{monthlength},
index af235ea..5608176 100755 (executable)
 use strict;
 use C4::Auth;
 use C4::Context;
-
+use C4::Output;
 use CGI;
 use C4::Interface::CGI::Output;
-
+use C4::Interface::CGI::Template;
 use C4::Koha;
 use C4::Letters;
 use C4::Serials;
@@ -34,14 +34,14 @@ my $dbh = C4::Context->dbh;
 
 my $input = new CGI;
 my $print = $input->param('print');
-
+my $template_name;
 
 my ($template, $loggedinuser, $cookie)
     = get_template_and_user({template_name => 'serials/viewalerts.tmpl',
                  query => $input,
                  type => "intranet",
                  authnotrequired => 0,
-                 flagsrequired => {catalogue => 1},
+                 flagsrequired => {serials => 1},
                  debug => 1,
                  });
 
index 8891886..f9f82fa 100755 (executable)
@@ -54,73 +54,104 @@ this script modify the status of a subscription to ACCEPTED or to REJECTED
 =item suggestedbyme
 
 =item op
+
 op can be :
  * aorr_confirm : to confirm accept or reject
  * delete_confirm : to confirm the deletion
-
+ * accepted : to display only accepted. 
 =back
 
 
 =cut
 
-
 use strict;
 require Exporter;
 use CGI;
-use HTML::Template;
-use C4::Auth;       # get_template_and_user
+
+use C4::Auth;    # get_template_and_user
 use C4::Interface::CGI::Output;
 use C4::Suggestions;
-
-my $input = new CGI;
-my $title = $input->param('title');
-my $author = $input->param('author');
-my $note = $input->param('note');
-my $copyrightdate =$input->param('copyrightdate');
-my $publishercode = $input->param('publishercode');
-my $volumedesc = $input->param('volumedesc');
+use C4::Koha;    # GetAuthorisedValue
+
+my $input           = new CGI;
+my $title           = $input->param('title');
+my $author          = $input->param('author');
+my $note            = $input->param('note');
+my $copyrightdate   = $input->param('copyrightdate');
+my $publishercode   = $input->param('publishercode');
+my $volumedesc      = $input->param('volumedesc');
 my $publicationyear = $input->param('publicationyear');
-my $place = $input->param('place');
-my $isbn = $input->param('isbn');
-my $status = $input->param('status');
-my $suggestedbyme = $input->param('suggestedbyme');
-my $op = $input->param('op');
-$op = 'else' unless $op;
+my $place           = $input->param('place');
+my $isbn            = $input->param('isbn');
+my $status          = $input->param('status');
+my $suggestedbyme   = $input->param('suggestedbyme');
+my $op              = $input->param('op') || "aorr_confirm";
 
 my $dbh = C4::Context->dbh;
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "suggestion/acceptorreject.tmpl",
-                            type => "intranet",
-                            query => $input,
-                            authnotrequired => 1,
-                            flagsrequired => {borrow => 1},
-                        });
-if ($op eq "aorr_confirm") {
-       my @suggestionlist = $input->param("aorr");
-       foreach my $suggestion (@suggestionlist) {
-               if ($suggestion =~ /(A|R)(.*)/) {
-                       my ($newstatus,$suggestionid) = ($1,$2);
-                       $newstatus="REJECTED" if $newstatus eq "R";
-                       $newstatus="ACCEPTED" if $newstatus eq "A";
-                       ModStatus($suggestionid,$newstatus,$loggedinuser);
-               }
-       }
-       $op="else";
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "suggestion/acceptorreject.tmpl",
+        type            => "intranet",
+        query           => $input,
+        authnotrequired => 1,
+        flagsrequired   => { catalogue => 1 },
+    }
+);
+
+my $suggestions;
+
+if ( $op eq "aorr_confirm" ) {
+    my @suggestionlist = $input->param("aorr");
+
+    foreach my $suggestion (@suggestionlist) {
+        if ( $suggestion =~ /(A|R)(.*)/ ) {
+            my ( $newstatus, $suggestionid ) = ( $1, $2 );
+            $newstatus = "REJECTED" if $newstatus eq "R";
+            $newstatus = "ACCEPTED" if $newstatus eq "A";
+            my $reason = $input->param( "reason" . $suggestionid );
+            if ( $reason eq "other" ) {
+                $reason = $input->param( "other-reason" . $suggestionid );
+            }
+            ModStatus( $suggestionid, $newstatus, $loggedinuser, '', $reason );
+        }
+    }
+    $op = "else";
+    $suggestions = &SearchSuggestion( "", "", "", "", 'ASKED', "" );
 }
 
-if ($op eq "delete_confirm") {
-       my @delete_field = $input->param("delete_field");
-       foreach my $delete_field (@delete_field) {
-               &DelSuggestion($loggedinuser,$delete_field);
-       }
-       $op='else';
+if ( $op eq "delete_confirm" ) {
+    my @delete_field = $input->param("delete_field");
+    foreach my $delete_field (@delete_field) {
+        &DelSuggestion( $loggedinuser, $delete_field );
+    }
+    $op = 'else';
+    $suggestions = &SearchSuggestion( "", "", "", "", 'ASKED', "" );
 }
 
-my $suggestions_loop= &SearchSuggestion("","","","",'ASKED',"");
-$template->param(suggestions_loop => $suggestions_loop,
-               "op_$op" => 1,
-               intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
-               intranetstylesheet => C4::Context->preference("intranetstylesheet"),
-               IntranetNav => C4::Context->preference("IntranetNav"),
+if ( $op eq "accepted" ) {
+    $suggestions = &GetSuggestionByStatus('ACCEPTED');
+    $template->param(done => 1);
+}
+
+if ( $op eq "rejected" ) {
+    $suggestions = &GetSuggestionByStatus('REJECTED');
+    $template->param(done => 1);
+}
+
+my $reasonsloop = GetAuthorisedValues("SUGGEST");
+my @suggestions_loop;
+foreach my $suggestion (@$suggestions) {
+    $suggestion->{'reasonsloop'} = $reasonsloop;
+    push @suggestions_loop, $suggestion;
+}
+
+$template->param(
+    suggestions_loop        => \@suggestions_loop,
+    "op_$op"                => 1,
+    intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
+    intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+    IntranetNav        => C4::Context->preference("IntranetNav"),
 );
+
 output_html_with_http_headers $input, $cookie, $template->output;
index a568b75..f436888 100755 (executable)
@@ -25,8 +25,8 @@ use CGI;
 use C4::Auth;
 use C4::Output;
 use C4::Interface::CGI::Output;
-use C4::Database;
-use HTML::Template;
+
+
 use C4::Context;
 use C4::Barcodes::PrinterConfig;
 
@@ -123,7 +123,7 @@ my ($template, $loggedinuser, $cookie)
                                         type => "intranet",
                                         query => $input,
                                         authnotrequired => 0,
-                                        flagsrequired => {parameters => 1},
+                                        flagsrequired => {tools => 1},
                                                 debug => 1,
                                       });
 
@@ -140,4 +140,4 @@ if ($input->param('error')) {
        $template->param(ERROR => 0);
 }
 # Shows the template with the real values replaced
-output_html_with_http_headers $input, $cookie, $template->output;
\ No newline at end of file
+output_html_with_http_headers $input, $cookie, $template->output;
index 7426602..f4eb510 100755 (executable)
@@ -27,7 +27,7 @@ use strict;
 use CGI;
 use C4::Context;
 use C4::Output;
-use HTML::Template;
+
 use PDF::API2;
 use PDF::API2::Page;
 use PDF::API2::PDF::Utils;
index 14eb66c..59352e3 100755 (executable)
@@ -4,9 +4,11 @@ use strict;
 use CGI;
 
 use C4::Auth;
-
+use C4::Output;
 use C4::Interface::CGI::Output;
-use C4::Calendar::Calendar;
+
+
+use C4::Calendar;
 
 my $input = new CGI;
 my $dbh = C4::Context->dbh();
@@ -19,7 +21,15 @@ my $year = $input->param('showYear');
 my $title = $input->param('showTitle');
 my $description = $input->param('showDescription');
 
-my $calendar = C4::Calendar::Calendar->new(branchcode => $branchcode);
+my $calendar = C4::Calendar->new(branchcode => $branchcode);
+
+$title || ($title = '');
+if ($description) {
+    $description =~ s/\r/\\r/g;
+    $description =~ s/\n/\\n/g;
+} else {
+    $description = '';
+}   
 
 if ($input->param('showOperation') eq 'exception') {
        $calendar->insert_exception_holiday(day => $day,
index 0abad2f..a012514 100755 (executable)
 #!/usr/bin/perl
-use strict;
 
+#
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+# $Id$
+
+use strict;
+require Exporter;
 use C4::Auth;
 use C4::Interface::CGI::Output;
-use C4::Biblio;
+use C4::Output;  # contains gettemplate
+use C4::Biblio;  # GetMarcBiblio GetXmlBiblio
 use CGI;
-use C4::Auth;
-use MARC::Record;
-use MARC::File::XML;
+use C4::Koha;    # GetItemTypes
+use C4::Branch;  # GetBranches
+
 my $query = new CGI;
 my $op=$query->param("op");
+my $dbh=C4::Context->dbh;
+my $marcflavour = C4::Context->preference("marcflavour");
+
 if ($op eq "export") {
-       print $query->header('Content-Type: text/marc');
-       my $start_bib = $query->param("start_bib");
-       my $end_bib = $query->param("end_bib");
-       my $dbh=C4::Context->dbh;
-       my $sth;
-       if ($start_bib && $end_bib) {
-               $sth=$dbh->prepare("select marcxml from biblio where biblionumber >=? and biblionumber <=? order by biblionumber");
-               $sth->execute($start_bib,$end_bib);
-       } elsif ($start_bib ) {
-               $sth=$dbh->prepare("select marcxml from biblio where biblionumber >=?  order by biblionumber");
-               $sth->execute($start_bib);
-       }else {
-               $sth=$dbh->prepare("select marcxml from biblio order by biblionumber");
-               $sth->execute();
-       }
-       while (my ($marc) = $sth->fetchrow) {
-my $record=MARC::Record->new_from_xml($marc,"UTF-8");
-       
-               print $record->as_usmarc;;
-       
-       }
-} else {
-       my ($template, $loggedinuser, $cookie)
-       = get_template_and_user({template_name => "tools/marc.tmpl",
-                                       query => $query,
-                                       type => "intranet",
-                                       authnotrequired => 0,
-                                       flagsrequired => {parameters => 1, management => 1, tools => 1},
-                                       debug => 1,
-                                       });
-       output_html_with_http_headers $query, $cookie, $template->output;
-}
 
+    print $query->header('Content-Type: text/marc');
+    
+    my $StartingBiblionumber  = $query->param("StartingBiblionumber");
+    my $EndingBiblionumber    = $query->param("EndingBiblionumber");
+    my $output_format         = $query->param("output_format");
+    my $branch                = $query->param("branch");
+    my $itemtype              = $query->param("itemtype");
+    my $start_callnumber      = $query->param("start_callnumber");
+    my $end_callnumber        = $query->param("end_callnumber");
+    my $dont_export_items     = $query->param("dont_export_item");
+    my $dont_export_fields    = $query->param("dont_export_fields");
+    my @sql_params;
+    my $query = " SELECT DISTINCT biblioitems.biblionumber
+                  FROM biblioitems,items
+                  WHERE biblioitems.biblionumber=items.biblionumber ";
+                  
+    if ( $StartingBiblionumber ) {
+        $query .= " AND biblioitems.biblionumber >= ? ";
+        push @sql_params, $StartingBiblionumber;
+    }
+    
+    if ( $EndingBiblionumber ) {
+        $query .= " AND biblioitems.biblionumber <= ? ";
+        push @sql_params, $EndingBiblionumber;    
+    }
+    
+    if ( $branch ) {
+        $query .= " AND biblioitems.biblionumber = items.biblionumber AND homebranch = ? ";
+        push @sql_params, $branch;
+    }
+    
+    if ( $start_callnumber ) {
+        $query .= " AND biblioitems.biblionumber = items.biblionumber AND itemcallnumber <= ? ";
+        push @sql_params, $start_callnumber;
+    }
+    
+    if ( $end_callnumber ) {
+        $query .= " AND biblioitems.biblionumber = items.biblionumber AND itemcallnumber >= ? ";
+        push @sql_params, $end_callnumber;
+    }
+    
+    if ( $itemtype ) {
+        $query .= " AND biblioitems.itemtype = ?";
+        push @sql_params, $itemtype;
+    }
+
+    my $sth = $dbh->prepare($query);
+    $sth->execute(@sql_params);
+    
+    while (my ($biblionumber) = $sth->fetchrow) {
+        my $record = GetMarcBiblio($biblionumber);
+        if ( $dont_export_items ) {
+            # now, find where the itemnumber is stored & extract only the item
+            my ( $itemnumberfield, $itemnumbersubfield ) =
+                MARCfind_marc_from_kohafield( $dbh, 'items.itemnumber', '' );
+
+            # and delete it.
+            foreach ($record->field($itemnumberfield)){
+                $record->delete_field($record->field($itemnumberfield));
+            }
+        }
+        
+        if ( $dont_export_fields ) {
+            my @fields = split " ", $dont_export_fields;
+            foreach ( @fields ) {
+                /^(\d*)(\w)?$/;
+                my $field = $1;
+                my $subfield = $2;
+                if( $subfield ) {
+                    $record->field($field)->delete_subfields($subfield);
+                }
+                else {
+                    $record->delete_field($record->field($field));
+                }
+            }
+        }
+        if ( $output_format eq "xml" ) {
+            print $record->as_xml_record($marcflavour);
+        }
+        else {
+            print $record->as_formatted; 
+        }
+    }
+    exit;
+    
+} # if export
+
+else {
+
+    my $itemtypes = GetItemTypes;
+    my @itemtypesloop;
+    foreach my $thisitemtype (sort keys %$itemtypes) {
+        my %row =
+            (
+                value => $thisitemtype,
+                description => $itemtypes->{$thisitemtype}->{'description'},
+            );
+       push @itemtypesloop, \%row;
+    }
+    
+    my $branches = GetBranches;
+    my $branch   = GetBranch($query,$branches);
+    my @branchloop;
+    foreach my $thisbranch (keys %$branches) {
+        my $selected = 1 if $thisbranch eq $branch;
+        my %row = (
+            value => $thisbranch,
+            selected => $selected,
+            branchname => $branches->{$thisbranch}->{'branchname'},
+       );
+       push @branchloop, \%row;
+    }
+    
+    my ($template, $loggedinuser, $cookie)
+    = get_template_and_user
+    (
+        {
+            template_name => "tools/export.tmpl",
+            query => $query,
+            type => "intranet",
+            authnotrequired => 0,
+            flagsrequired => {tools => 1},
+            debug => 1,
+         }
+    );
+    
+    $template->param(
+        branchloop   => \@branchloop,
+        itemtypeloop => \@itemtypesloop
+    );
+    
+    output_html_with_http_headers $query, $cookie, $template->output;
+}
index c2c03a3..6994f87 100755 (executable)
@@ -1,18 +1,44 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
+#####Sets holiday periods for each branch. Datedues will be extended if branch is closed -TG
 use strict;
 use CGI;
 
 use C4::Auth;
-
+use C4::Output;
 use C4::Interface::CGI::Output;
 
-use C4::Calendar::Calendar;
+
+use C4::Calendar;
 
 my $input = new CGI;
-my $branch = $input->param('branch');
-$branch=C4::Context->preference('defaultBranch') unless $branch;
+#my $branch = $input->param('branch');
+my $branch=C4::Context->preference('defaultbranch') || $input->param('branch');
 my $dbh = C4::Context->dbh();
+# Get the template to use
+my ($template, $loggedinuser, $cookie)
+    = get_template_and_user({template_name => "tools/holidays.tmpl",
+                             type => "intranet",
+                             query => $input,
+                             authnotrequired => 0,
+                             flagsrequired => {tools => 1},
+                             debug => 1,
+                           });
 
 # Set all the branches.
 my $branches = $dbh->prepare("select branchcode, branchname from branches");
@@ -20,74 +46,67 @@ $branches->execute;
 # It creates a list of branches
 my %list;
 while (my ($branchcode, $branchname) = $branches->fetchrow) {
-       $list{$branchcode} = $branchname;
+    $list{$branchcode} = $branchname;
 }
 my @listValues = keys(%list);
 if (!defined($branch)) {
-       $branch =$listValues[4];
+    $branch =$listValues[4];
 }
-my $branchesList = CGI::scrolling_list(-name => 'branch', -id=>'branch',
-                                              -values => \@listValues,
-                                                  -labels => \%list,
-                                                  -size => 1,
-                                        -default => [$branch],
-                                                  -multiple => 0,
-                                        -onChange => "changeBranch()");
+my $branchesList = CGI::scrolling_list(-name => 'branch',
+                                       -values => \@listValues,
+                                       -labels => \%list,
+                                       -size => 1,
+                                       -default => [$branch],
+                                       -multiple => 0,
+                                       -id => "branch",
+                                       -onChange => "changeBranch()");
 
 $branches->finish;
 
 # Get all the holidays
-my $calendar = C4::Calendar::Calendar->new(branchcode => $branch);
+# warn "BRANCH : $branch";
+my $calendar = C4::Calendar->new(branchcode => $branch);
 my $week_days_holidays = $calendar->get_week_days_holidays();
 my @week_days;
 foreach my $weekday (keys %$week_days_holidays) {
-       my %week_day;
-       %week_day = (KEY => $weekday,
-                        TITLE => $week_days_holidays->{$weekday}{title},
-                        DESCRIPTION => $week_days_holidays->{$weekday}{description});
-       push @week_days, \%week_day;
+# warn "WEEK DAY : $weekday";
+    my %week_day;
+    %week_day = (KEY => $weekday,
+                 TITLE => $week_days_holidays->{$weekday}{title},
+                 DESCRIPTION => $week_days_holidays->{$weekday}{description});
+    push @week_days, \%week_day;
 }
 
 my $day_month_holidays = $calendar->get_day_month_holidays();
 my @day_month_holidays;
 foreach my $monthDay (keys %$day_month_holidays) {
-       my %day_month;
-       %day_month = (KEY => $monthDay,
-                         TITLE => $day_month_holidays->{$monthDay}{title},
-                         DESCRIPTION => $day_month_holidays->{$monthDay}{description});
-       push @day_month_holidays, \%day_month;
+    my %day_month;
+    %day_month = (KEY => $monthDay,
+                  TITLE => $day_month_holidays->{$monthDay}{title},
+                  DESCRIPTION => $day_month_holidays->{$monthDay}{description});
+    push @day_month_holidays, \%day_month;
 }
 
 my $exception_holidays = $calendar->get_exception_holidays();
 my @exception_holidays;
 foreach my $yearMonthDay (keys %$exception_holidays) {
-       my %exception_holiday;
-       %exception_holiday = (KEY => $yearMonthDay,
-                                 TITLE => $exception_holidays->{$yearMonthDay}{title},
-                                 DESCRIPTION => $exception_holidays->{$yearMonthDay}{description});
-       push @exception_holidays, \%exception_holiday;
+    my %exception_holiday;
+    %exception_holiday = (KEY => $yearMonthDay,
+                          TITLE => $exception_holidays->{$yearMonthDay}{title},
+                          DESCRIPTION => $exception_holidays->{$yearMonthDay}{description});
+    push @exception_holidays, \%exception_holiday;
 }
 
 my $single_holidays = $calendar->get_single_holidays();
 my @holidays;
 foreach my $yearMonthDay (keys %$single_holidays) {
-       my %holiday;
-       %holiday = (KEY => $yearMonthDay,
-                       TITLE => $single_holidays->{$yearMonthDay}{title},
-                       DESCRIPTION => $single_holidays->{$yearMonthDay}{description});
-       push @holidays, \%holiday;
+    my %holiday;
+    %holiday = (KEY => $yearMonthDay,
+                TITLE => $single_holidays->{$yearMonthDay}{title},
+                DESCRIPTION => $single_holidays->{$yearMonthDay}{description});
+    push @holidays, \%holiday;
 }
 
-# Get the template to use
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "tools/holidays.tmpl",
-                                        type => "intranet",
-                                        query => $input,
-                                        authnotrequired => 0,
-                                        flagsrequired => {parameters => 1},
-                                                debug => 1,
-                                      });
-
 # Replace the template values with the real ones
 $template->param(BRANCHES => $branchesList);
 $template->param(WEEK_DAYS_LOOP => \@week_days);
@@ -97,4 +116,4 @@ $template->param(DAY_MONTH_HOLIDAYS_LOOP => \@day_month_holidays);
 $template->param(branch => $branch);
 
 # Shows the template with the real values replaced
-output_html_with_http_headers $input, $cookie, $template->output;
\ No newline at end of file
+output_html_with_http_headers $input, $cookie, $template->output;
index de971a0..569dc6c 100755 (executable)
@@ -31,17 +31,25 @@ use strict;
 
 # standard or CPAN modules used
 use CGI;
+use DBI;
 
 # Koha modules used
 use C4::Context;
+use C4::Output;
 use C4::Interface::CGI::Output;
+use C4::Input;
+use C4::Biblio;
+use MARC::File::USMARC;
+
+use C4::Output;
 use C4::Auth;
 use C4::Breeding;
 
 #------------------
 # Constants
 
-
+my $includes = C4::Context->config('includes') ||
+       "/usr/local/www/hdl/htdocs/includes";
 
 # HTML colors for alternating lines
 my $lc1='#dddddd';
@@ -61,11 +69,11 @@ my $overwrite_biblio = $input->param('overwrite_biblio');
 my $filename = $input->param('filename');
 my $syntax = $input->param('syntax');
 my ($template, $loggedinuser, $cookie)
-       = get_template_and_user({template_name => "tools/breeding.tmpl",
+       = get_template_and_user({template_name => "tools/import.tmpl",
                                        query => $input,
                                        type => "intranet",
                                        authnotrequired => 0,
-                                       flagsrequired => {parameters => 1, management => 1, tools => 1},
+                                       flagsrequired => {tools => 1},
                                        debug => 1,
                                        });
 
@@ -76,7 +84,7 @@ if ($uploadmarc && length($uploadmarc)>0) {
        while (<$uploadmarc>) {
                $marcrecord.=$_;
        }
-       my ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported) = ImportBreeding($marcrecord,$overwrite_biblio,$filename,$syntax,"");
+       my ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported) = ImportBreeding($marcrecord,$overwrite_biblio,$filename,$syntax,int(rand(99999)));
 
        $template->param(imported => $imported,
                                                        alreadyindb => $alreadyindb,
@@ -88,16 +96,34 @@ if ($uploadmarc && length($uploadmarc)>0) {
 }
 
 output_html_with_http_headers $input, $cookie, $template->output;
-my $menu;
-my $file;
 
 
 #---------------
 # log cleared, as marcimport is (almost) rewritten from scratch.
 # $Log$
-# Revision 1.3  2006/09/27 21:19:22  tgarip1957
-# Finalized XML version for intranet
+# Revision 1.4  2007/03/09 15:14:47  tipaul
+# rel_3_0 moved to HEAD
+#
+# Revision 1.1.2.4  2006/12/22 17:13:49  tipaul
+# removing "management" permission, that is useless (replaced by tools & admin)
+#
+# Revision 1.1.2.3  2006/12/18 16:35:20  toins
+# removing use HTML::Template from *.pl.
+#
+# Revision 1.1.2.2  2006/10/03 12:27:32  toins
+# the script was written twice into the file !
+#
+# Revision 1.1.2.1  2006/09/26 13:42:54  toins
+# fix wrong link to breeding.tmpl
+#
+# Revision 1.1  2006/02/24 11:52:38  hdl
+# Adding tools directory template and scripts
+# Changing barcodes, export and import and letters directory.
+# Changing export script name (marc.pl) to export.pl
+# Changing import script name (breeding.pl) to import.pl
 #
-# Revision 1.2.4.1  2005/04/07 10:10:52  tipaul
-# copying processz3950queue from 2.0 branch. The 2.2 version misses an important fix
+# Revision 1.4  2005/05/04 08:52:13  tipaul
+# synch'ing 2.2 and head
 #
+# Revision 1.3  2005/03/23 09:57:47  doxulting
+# Adding a parameter to allow acces to people with management/tools flags
index 605a86b..1169d3b 100755 (executable)
 
 use strict;
 use CGI;
-
 use C4::Auth;
 use C4::Koha;
 use C4::Context;
 use C4::Output;
 use C4::Interface::CGI::Output;
 use C4::NewsChannels;
-
+use C4::Languages;
+use Date::Calc qw/Date_to_Days Today/;
 
 my $cgi = new CGI;
 
-my $id         = $cgi->param('id');
-my $title      = $cgi->param('title');
-my $new                = $cgi->param('new');
-my $lang       = $cgi->param('lang');
+my $id             = $cgi->param('id');
+my $title          = $cgi->param('title');
+my $new            = $cgi->param('new');
+my $expirationdate = $cgi->param('expirationdate');
+my $number         = $cgi->param('number');
+my $lang           = $cgi->param('lang');
+
 my $new_detail = get_opac_new($id);
 
-my ($template, $borrowernumber, $cookie)
-    = get_template_and_user({template_name => "tools/koha-news.tmpl",
-                            query => $cgi,
-                            type => "intranet",
-                            authnotrequired => 0,
-                            flagsrequired => {management => 1},
-                            debug => 1,
-                            });
+my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
+    {
+        template_name   => "tools/koha-news.tmpl",
+        query           => $cgi,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { tools => 1 },
+        debug           => 1,
+    }
+);
 
 # get lang list
 my @lang_list;
-
-foreach my $language (getalllanguages()) {
-       push @lang_list, { language => $language,
-                                               selected => ($new_detail->{lang} eq $language?1:0),
-                                       };
+my $tlangs = getTranslatedLanguages() ;
+foreach my $language ( @$tlangs ) {
+    push @lang_list,
+      {
+        language => $language->{'language_code'},
+        selected => ( $new_detail->{lang} eq $language->{'language_code'} ? 1 : 0 ),
+      };
 }
-$template->param(lang_list => \@lang_list);
-
-my $op = $cgi->param('op');
-
-if ($op eq 'add_form') {
-       $template->param(add_form => 1);
-       if ($id) {
-               $template->param(op => 'edit');
-               $template->param($new_detail);
-               $template->param(id => $new_detail->{'idnew'});
-       } else {
-               $template->param(op => 'add');
-       }
-       
-} elsif ($op eq 'add') {
-
-       add_opac_new($title, $new, $lang);
-       print $cgi->redirect('/cgi-bin/koha/tools/koha-news.pl');
 
-} elsif ($op eq 'edit') {
+$template->param( lang_list => \@lang_list );
 
-       upd_opac_new($id, $title, $new, $lang);
-       print $cgi->redirect('/cgi-bin/koha/tools/koha-news.pl');
-
-} elsif ($op eq 'del') {
-       my @ids = $cgi->param('ids');
-       del_opac_new(join ",", @ids);
-       print $cgi->redirect('/cgi-bin/koha/tools/koha-news.pl');
-
-} else { 
+my $op = $cgi->param('op');
 
-       my ($opac_news_count, $opac_news) = &get_opac_news(undef, $lang);
-       $template->param($lang => 1);
-       $template->param(opac_news => $opac_news);
-       $template->param(opac_news_count => $opac_news_count);
+if ( $op eq 'add_form' ) {
+    $template->param( add_form => 1 );
+    if ($id) {
+        $template->param( 
+            op => 'edit',
+            id => $new_detail->{'idnew'}
+        );
+        $template->param($new_detail);
+    }
+    else {
+        $template->param( op => 'add' );
+    }
+}
+elsif ( $op eq 'add' ) {
+    add_opac_new( $title, $new, $lang, $expirationdate, $number );
+    print $cgi->redirect("/cgi-bin/koha/tools/koha-news.pl");
+}
+elsif ( $op eq 'edit' ) {
+    upd_opac_new( $id, $title, $new, $lang, $expirationdate, $number );
+    print $cgi->redirect("/cgi-bin/koha/tools/koha-news.pl");
+}
+elsif ( $op eq 'del' ) {
+    my @ids = $cgi->param('ids');
+    del_opac_new( join ",", @ids );
+    print $cgi->redirect("/cgi-bin/koha/tools/koha-news.pl");
+}
 
+else {
+
+    my ( $opac_news_count, $opac_news ) = &get_opac_news( undef, $lang );
+    
+    foreach my $new ( @$opac_news ) {
+        next unless $new->{'expirationdate'};
+        next if $new->{'expirationdate'} eq '0000-00-00';
+        if (Date_to_Days( split "-" ,$new->{'expirationdate'} ) < Date_to_Days(&Today) ){
+            $new->{'hasexpirated'} = 1;
+        }
+    }
+    
+    $template->param(
+        $lang           => 1,
+        opac_news       => $opac_news,
+        opac_news_count => $opac_news_count 
+    );
 }
 
 output_html_with_http_headers $cgi, $cookie, $template->output;
index 0ea6aba..c4346fd 100755 (executable)
@@ -44,26 +44,25 @@ use C4::Auth;
 use C4::Context;
 use C4::Output;
 use C4::Interface::CGI::Output;
-use C4::Search;
-use HTML::Template;
+
 
 sub StringSearch  {
-       my ($env,$searchstring,$type)=@_;
-       my $dbh = C4::Context->dbh;
-       $searchstring=~ s/\'/\\\'/g;
-       my @data=split(' ',$searchstring);
-       my $count=@data;
-       my $sth=$dbh->prepare("Select * from letter where (code like ?) order by module,code");
-       $sth->execute("$data[0]%");
-       my @results;
-       my $cnt=0;
-       while (my $data=$sth->fetchrow_hashref){
-       push(@results,$data);
-       $cnt ++;
-       }
-       #  $sth->execute;
-       $sth->finish;
-       return ($cnt,\@results);
+    my ($env,$searchstring,$type)=@_;
+    my $dbh = C4::Context->dbh;
+    $searchstring=~ s/\'/\\\'/g;
+    my @data=split(' ',$searchstring);
+    my $count=@data;
+    my $sth=$dbh->prepare("Select * from letter where (code like ?) order by module,code");
+    $sth->execute("$data[0]%");
+    my @results;
+    my $cnt=0;
+    while (my $data=$sth->fetchrow_hashref){
+    push(@results,$data);
+    $cnt ++;
+    }
+    #  $sth->execute;
+    $sth->finish;
+    return ($cnt,\@results);
 }
 
 my $input = new CGI;
@@ -72,6 +71,7 @@ my $offset=$input->param('offset');
 my $script_name="/cgi-bin/koha/tools/letter.pl";
 my $code=$input->param('code');
 my $module = $input->param('module');
+my $content = $input->param('content');
 my $pagesize=20;
 my $op = $input->param('op');
 $searchfield=~ s/\,//g;
@@ -79,150 +79,197 @@ my $dbh = C4::Context->dbh;
 
 my ($template, $borrowernumber, $cookie)
     = get_template_and_user({template_name => "tools/letter.tmpl",
-                            query => $input,
-                            type => "intranet",
-                            authnotrequired => 0,
-                            flagsrequired => {tools => 1},
-                            debug => 1,
-                            });
+                query => $input,
+                type => "intranet",
+                authnotrequired => 0,
+                flagsrequired => {tools => 1},
+                debug => 1,
+                });
 
 if ($op) {
 $template->param(script_name => $script_name,
-                                               $op              => 1); # we show only the TMPL_VAR names $op
+                        $op              => 1); # we show only the TMPL_VAR names $op
 } else {
 $template->param(script_name => $script_name,
-                                               else              => 1); # we show only the TMPL_VAR names $op
+                        else              => 1); # we show only the TMPL_VAR names $op
 }
 
 $template->param(action => $script_name);
 ################## ADD_FORM ##################################
 # called by default. Used to create form to add or  modify a record
 if ($op eq 'add_form') {
-       #---- if primkey exists, it's a modify action, so read values to modify...
-       my $letter;
-       if ($code) {
-               my $sth=$dbh->prepare("select * from letter where module=? and code=?");
-               $sth->execute($module,$code);
-               $letter=$sth->fetchrow_hashref;
-               $sth->finish;
-       }
-       # build field list
-       my @SQLfieldname;
-       my %line = ('value' => "LibrarianFirstname", 'text' => 'LibrarianFirstname');
-       push @SQLfieldname, \%line;
-       my %line = ('value' => "LibrarianSurname", 'text' => 'LibrarianSurname');
-       push @SQLfieldname, \%line;
-       my %line = ('value' => "LibrarianEmailaddress", 'text' => 'LibrarianEmailaddress');
-       push @SQLfieldname, \%line;
-       my $sth2=$dbh->prepare("SHOW COLUMNS from branches");
-       $sth2->execute;
-       my %line = ('value' => "", 'text' => '---BRANCHES---');
-       push @SQLfieldname, \%line;
-       while ((my $field) = $sth2->fetchrow_array) {
-               my %line = ('value' => "branches.".$field, 'text' => "branches.".$field);
-               push @SQLfieldname, \%line;
-       }
-       my $sth2=$dbh->prepare("SHOW COLUMNS from biblio");
-       $sth2->execute;
-       my %line = ('value' => "", 'text' => '---BIBLIO---');
+    #---- if primkey exists, it's a modify action, so read values to modify...
+    my $letter;
+    if ($code) {
+        my $sth=$dbh->prepare("select * from letter where module=? and code=?");
+        $sth->execute($module,$code);
+        $letter=$sth->fetchrow_hashref;
+        $sth->finish;
+    }
+    # build field list
+    my @SQLfieldname;
+    my %line = ('value' => "LibrarianFirstname", 'text' => 'LibrarianFirstname');
+    push @SQLfieldname, \%line;
+    my %line = ('value' => "LibrarianSurname", 'text' => 'LibrarianSurname');
+    push @SQLfieldname, \%line;
+    my %line = ('value' => "LibrarianEmailaddress", 'text' => 'LibrarianEmailaddress');
+    push @SQLfieldname, \%line;
+    my $sth2=$dbh->prepare("SHOW COLUMNS from branches");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BRANCHES---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "branches.".$field, 'text' => "branches.".$field);
+        push @SQLfieldname, \%line;
+    }
+    # add acquisition specific tables
+    if (index($module,"acquisition")>0){
+    my $sth2=$dbh->prepare("SHOW COLUMNS from aqbooksellers");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BOOKSELLERS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "aqbooksellers.".$field, 'text' => "aqbooksellers.".$field);
+        push @SQLfieldname, \%line;
+    }
+    my $sth2=$dbh->prepare("SHOW COLUMNS from aqorders");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---ORDERS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "aqorders.".$field, 'text' => "aqorders.".$field);
+        push @SQLfieldname, \%line;
+    }
+    # add issues specific tables
+    }elsif (index($module,"issues")>0){
+    my $sth2=$dbh->prepare("SHOW COLUMNS from aqbooksellers");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BOOKSELLERS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "aqbooksellers.".$field, 'text' => "aqbooksellers.".$field);
+        push @SQLfieldname, \%line;
+    }
+    my $sth2=$dbh->prepare("SHOW COLUMNS from serial");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---SERIALS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "serial.".$field, 'text' => "serial.".$field);
+        push @SQLfieldname, \%line;
+    }
+    my $sth2=$dbh->prepare("SHOW COLUMNS from subscription");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---SUBSCRIPTION---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "subscription.".$field, 'text' => "subscription.".$field);
+        push @SQLfieldname, \%line;
+    }
+    # add biblio specific tables.
+    } else {
+    my $sth2=$dbh->prepare("SHOW COLUMNS from biblio");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BIBLIO---');
 
-       push @SQLfieldname, \%line;
-       while ((my $field) = $sth2->fetchrow_array) {
-               # note : %line is redefined, otherwise \%line contains the same value for every entry of the list
-               my %line = ('value' => "biblio.".$field, 'text' => "biblio.".$field);
-               push @SQLfieldname, \%line;
-       }
-       my $sth2=$dbh->prepare("SHOW COLUMNS from biblioitems");
-       $sth2->execute;
-       my %line = ('value' => "", 'text' => '---BIBLIOITEMS---');
-       push @SQLfieldname, \%line;
-       while ((my $field) = $sth2->fetchrow_array) {
-               my %line = ('value' => "biblioitems.".$field, 'text' => "biblioitems.".$field);
-               push @SQLfieldname, \%line;
-       }
-       my %line = ('value' => "", 'text' => '---ITEMS---');
-       push @SQLfieldname, \%line;
-       my %line = ('value' => "items.content", 'text' => 'items.content');
-       push @SQLfieldname, \%line;
-       
-       my $sth2=$dbh->prepare("SHOW COLUMNS from borrowers");
-       $sth2->execute;
-       my %line = ('value' => "", 'text' => '---BORROWERS---');
-       push @SQLfieldname, \%line;
-       while ((my $field) = $sth2->fetchrow_array) {
-               my %line = ('value' => "borrowers.".$field, 'text' => "borrowers.".$field);
-               push @SQLfieldname, \%line;
-       }
-       if ($code) {
-           $template->param(modify => 1);
-           $template->param(code => $letter->{code});
-       } else {
-           $template->param(adding => 1);
-       }
-       $template->param(name => $letter->{name},title => $letter->{title},
-                                       content => $letter->{content},
-                                       $letter->{module} => 1,
-                                       SQLfieldname => \@SQLfieldname,);
-                                                                                                       # END $OP eq ADD_FORM
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        # note : %line is redefined, otherwise \%line contains the same value for every entry of the list
+        my %line = ('value' => "biblio.".$field, 'text' => "biblio.".$field);
+        push @SQLfieldname, \%line;
+    }
+    my $sth2=$dbh->prepare("SHOW COLUMNS from biblioitems");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BIBLIOITEMS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "biblioitems.".$field, 'text' => "biblioitems.".$field);
+        push @SQLfieldname, \%line;
+    }
+    my %line = ('value' => "", 'text' => '---ITEMS---');
+    push @SQLfieldname, \%line;
+    my %line = ('value' => "items.content", 'text' => 'items.content');
+    push @SQLfieldname, \%line;
+    
+    my $sth2=$dbh->prepare("SHOW COLUMNS from borrowers");
+    $sth2->execute;
+    my %line = ('value' => "", 'text' => '---BORROWERS---');
+    push @SQLfieldname, \%line;
+    while ((my $field) = $sth2->fetchrow_array) {
+        my %line = ('value' => "borrowers.".$field, 'text' => "borrowers.".$field);
+        push @SQLfieldname, \%line;
+    }
+    }
+    if ($code) {
+        $template->param(modify => 1);
+        $template->param(code => $letter->{code});
+    } else {
+        $template->param(adding => 1);
+    }
+    $template->param(name => $letter->{name},title => $letter->{title},
+                    content => ($content?$content:$letter->{content}),
+                    ($module?$module:$letter->{module}) => 1,
+                    SQLfieldname => \@SQLfieldname,);
+                                                    # END $OP eq ADD_FORM
 ################## ADD_VALIDATE ##################################
 # called by add_form, used to insert/modify data in DB
 } elsif ($op eq 'add_validate') {
-       my $dbh = C4::Context->dbh;
-       my $sth=$dbh->prepare("replace letter (module,code,name,title,content) values (?,?,?,?,?)");
-       $sth->execute($input->param('module'),$input->param('code'),$input->param('name'),$input->param('title'),$input->param('content'));
-       $sth->finish;
-        print $input->redirect("letter.pl");
-        exit;
+    my $dbh = C4::Context->dbh;
+    my $sth=$dbh->prepare("replace letter (module,code,name,title,content) values (?,?,?,?,?)");
+    $sth->execute($input->param('module'),$input->param('code'),$input->param('name'),$input->param('title'),$input->param('content'));
+    $sth->finish;
+    print $input->redirect("letter.pl");
+    exit;
 # END $OP eq ADD_VALIDATE
 ################## DELETE_CONFIRM ##################################
 # called by default form, used to confirm deletion of data in DB
 } elsif ($op eq 'delete_confirm') {
-       my $dbh = C4::Context->dbh;
-       my $sth=$dbh->prepare("select * from letter where code=?");
-       $sth->execute($code);
-       my $data=$sth->fetchrow_hashref;
-       $sth->finish;
-       $template->param(module => $data->{module});
-       $template->param(code => $code);
-       $template->param(name => $data->{'name'});
-       $template->param(content => $data->{'content'});
-                                                                                                       # END $OP eq DELETE_CONFIRM
+    my $dbh = C4::Context->dbh;
+    my $sth=$dbh->prepare("select * from letter where code=?");
+    $sth->execute($code);
+    my $data=$sth->fetchrow_hashref;
+    $sth->finish;
+    $template->param(module => $data->{module});
+    $template->param(code => $code);
+    $template->param(name => $data->{'name'});
+    $template->param(content => $data->{'content'});
+                                                    # END $OP eq DELETE_CONFIRM
 ################## DELETE_CONFIRMED ##################################
 # called by delete_confirm, used to effectively confirm deletion of data in DB
 } elsif ($op eq 'delete_confirmed') {
-       my $dbh = C4::Context->dbh;
-       my $code=uc($input->param('code'));
-       my $module=$input->param('module');
-       my $sth=$dbh->prepare("delete from letter where module=? and code=?");
-       $sth->execute($module,$code);
-       $sth->finish;
-        print $input->redirect("letter.pl");
-        return;
-                                                                                                       # END $OP eq DELETE_CONFIRMED
+    my $dbh = C4::Context->dbh;
+    my $code=uc($input->param('code'));
+    my $module=$input->param('module');
+    my $sth=$dbh->prepare("delete from letter where module=? and code=?");
+    $sth->execute($module,$code);
+    $sth->finish;
+    print $input->redirect("letter.pl");
+    return;
+                                                    # END $OP eq DELETE_CONFIRMED
 ################## DEFAULT ##################################
 } else { # DEFAULT
-       if  ($searchfield ne '') {
-               $template->param(search => 1);
-               $template->param(searchfield => $searchfield);
-       }
-       my $env;
-       my ($count,$results)=StringSearch($env,$searchfield,'web');
-       my $toggle="white";
-       my @loop_data =();
-       for (my $i=$offset; $i < ($offset+$pagesize<$count?$offset+$pagesize:$count); $i++){
-               if ($toggle eq 'white'){
-                       $toggle="#ffffcc";
-               } else {
-                       $toggle="white";
-               }
-          my %row_data;
-          $row_data{toggle} = $toggle;
-          $row_data{module} = $results->[$i]{'module'};
-          $row_data{code} = $results->[$i]{'code'};
-          $row_data{name} = $results->[$i]{'name'};
-          push(@loop_data, \%row_data);
-       }
-       $template->param(letter => \@loop_data);
+    if  ($searchfield ne '') {
+            $template->param(search => 1);
+        $template->param(searchfield => $searchfield);
+    }
+    my $env;
+    my ($count,$results)=StringSearch($env,$searchfield,'web');
+    my $toggle="white";
+    my @loop_data =();
+    for (my $i=$offset; $i < ($offset+$pagesize<$count?$offset+$pagesize:$count); $i++){
+        if ($toggle eq 'white'){
+                $toggle="#ffffcc";
+        } else {
+                $toggle="white";
+        }
+    my %row_data;
+    $row_data{toggle} = $toggle;
+    $row_data{module} = $results->[$i]{'module'};
+    $row_data{code} = $results->[$i]{'code'};
+    $row_data{name} = $results->[$i]{'name'};
+    push(@loop_data, \%row_data);
+    }
+    $template->param(letter => \@loop_data);
 } #---- END $OP eq DEFAULT
 
 output_html_with_http_headers $input, $cookie, $template->output;
index e8fefe4..a22a19e 100755 (executable)
@@ -6,7 +6,9 @@ use CGI;
 use C4::Auth;
 use C4::Output;
 use C4::Interface::CGI::Output;
-use C4::Calendar::Calendar;
+
+
+use C4::Calendar;
 
 my $input = new CGI;
 my $dbh = C4::Context->dbh();
@@ -19,7 +21,15 @@ my $year = $input->param('newYear');
 my $title = $input->param('newTitle');
 my $description = $input->param('newDescription');
 
-my $calendar = C4::Calendar::Calendar->new(branchcode => $branchcode);
+$title || ($title = '');
+if ($description) {
+       $description =~ s/\r/\\r/g;
+       $description =~ s/\n/\\n/g;
+} else {
+       $description = '';
+}
+
+my $calendar = C4::Calendar->new(branchcode => $branchcode);
 
 if ($input->param('newOperation') eq 'weekday') {
        $calendar->insert_week_day_holiday(weekday => $weekday,
@@ -38,4 +48,4 @@ if ($input->param('newOperation') eq 'weekday') {
                                                             description => $description);
 
 }
-print $input->redirect("/cgi-bin/koha/tools/holidays.pl?branch=$branchcode");
\ No newline at end of file
+print $input->redirect("/cgi-bin/koha/tools/holidays.pl?branch=$branchcode");
index c12b9f0..75948b2 100755 (executable)
 use strict;
 use CGI;
 use C4::Context;
+use C4::Output;
+
 use C4::Auth;
+use C4::Output;
 use C4::Koha;
 use C4::Interface::CGI::Output;
-
+use C4::Branch; # GetBranches
+use C4::Letters;
 
 my $input = new CGI;
 my $dbh = C4::Context->dbh;
@@ -118,7 +122,7 @@ if ($op eq 'save') {
        }
        unless ($err) {$template->param(datasaved=>1);}
 }
-my $branches = getbranches;
+my $branches = GetBranches();
 my @branchloop;
 foreach my $thisbranch (keys %$branches) {
        my $selected = 1 if $thisbranch eq $branch;
@@ -129,7 +133,9 @@ foreach my $thisbranch (keys %$branches) {
        push @branchloop, \%row;
 }
 
-my ($countletters,$letters) = getletters("circulation");
+my $letters = GetLetters("circulation");
+
+my $countletters = scalar $letters;
 
 my $sth=$dbh->prepare("Select description,categorycode from categories where overduenoticerequired>0 order by description");
 $sth->execute;
index 5dba03e..a29ff78 100755 (executable)
@@ -27,6 +27,7 @@ use CGI;
 use C4::Context;
 use C4::Output;
 use C4::Auth;
+
 use PDF::API2;
 use PDF::API2::Page;
 use PDF::API2::PDF::Utils;
index d4a421a..1a87fd6 100755 (executable)
@@ -1,19 +1,35 @@
 #!/usr/bin/perl
 
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it under the
+# terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
+# Suite 330, Boston, MA  02111-1307 USA
+
 use strict;
 use CGI;
 use C4::Auth;
 use C4::Interface::CGI::Output;
 
-
 my $query = new CGI;
-my ($template, $loggedinuser, $cookie)
-    = get_template_and_user({template_name => "tools/tools-home.tmpl",
-                            query => $query,
-                            type => "intranet",
-                            authnotrequired => 0,
-                            flagsrequired => {tools => 1},
-                            debug => 1,
-                            });
+my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
+    {
+        template_name   => "tools/tools-home.tmpl",
+        query           => $query,
+        type            => "intranet",
+        authnotrequired => 0,
+        flagsrequired   => { tools => 1 },
+        debug           => 1,
+    }
+);
 
 output_html_with_http_headers $query, $cookie, $template->output;
index 34f3e38..361674f 100755 (executable)
@@ -41,8 +41,8 @@ my (
 
 my $silent;
 GetOptions(
-       's' =>\$silent
-       );
+    's' =>\$silent
+    );
 my $dbh = C4::Context->dbh;
 print "connected to your DB. Checking & modifying it\n" unless $silent;
 $|=1; # flushes output
@@ -67,141 +67,192 @@ my %requiretables = (
                              itemtypecodes text default '',
                              PRIMARY KEY (mediatypecode)
                             )",
-    action_logs        => "(
-                                   `timestamp` TIMESTAMP NOT NULL ,
-                                   `user` INT( 11 ) NOT NULL ,
-                                   `module` TEXT default '',
-                                   `action` TEXT default '' ,
-                                   `object` INT(11) default '' ,
-                                   `info` TEXT default '' ,
-                                   PRIMARY KEY ( `timestamp` , `user` )
-                           )",
-       letter          => "(
-                                       module varchar(20) NOT NULL default '',
-                                       code varchar(20) NOT NULL default '',
-                                       name varchar(100) NOT NULL default '',
-                                       title varchar(200) NOT NULL default '',
-                                       content text,
-                                       PRIMARY KEY  (module,code)
-                               )",
-       alert           =>"(
-                                       alertid int(11) NOT NULL auto_increment,
-                                       borrowernumber int(11) NOT NULL default '0',
-                                       type varchar(10) NOT NULL default '',
-                                       externalid varchar(20) NOT NULL default '',
-                                       PRIMARY KEY  (alertid),
-                                       KEY borrowernumber (borrowernumber),
-                                       KEY type (type,externalid)
-                               )",
-       opac_news => "(
-                               `idnew` int(10) unsigned NOT NULL auto_increment,
-                               `title` varchar(250) NOT NULL default '',
-                               `new` text NOT NULL,
-                               `lang` varchar(4) NOT NULL default '',
-                               `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
-                               PRIMARY KEY  (`idnew`)
-                               )",
-       repeatable_holidays => "(
-                               `id` int(11) NOT NULL auto_increment,
-                               `branchcode` varchar(4) NOT NULL default '',
-                               `weekday` smallint(6) default NULL,
-                               `day` smallint(6) default NULL,
-                               `month` smallint(6) default NULL,
-                               `title` varchar(50) NOT NULL default '',
-                               `description` text NOT NULL,
-                               PRIMARY KEY  (`id`)
-                               )",
-       special_holidays => "(
-                               `id` int(11) NOT NULL auto_increment,
-                               `branchcode` varchar(4) NOT NULL default '',
-                               `day` smallint(6) NOT NULL default '0',
-                               `month` smallint(6) NOT NULL default '0',
-                               `year` smallint(6) NOT NULL default '0',
-                               `isexception` smallint(1) NOT NULL default '1',
-                               `title` varchar(50) NOT NULL default '',
-                               `description` text NOT NULL,
-                               PRIMARY KEY  (`id`)
-                               )",
-       overduerules    =>"(`branchcode` varchar(255) NOT NULL default '',
-                                       `categorycode` char(2) NOT NULL default '',
-                                       `delay1` int(4) default '0',
-                                       `letter1` varchar(20) default NULL,
-                                       `debarred1` char(1) default '0',
-                                       `delay2` int(4) default '0',
-                                       `debarred2` char(1) default '0',
-                                       `letter2` varchar(20) default NULL,
-                                       `delay3` int(4) default '0',
-                                       `letter3` varchar(20) default NULL,
-                                       `debarred3` int(1) default '0',
-                                       PRIMARY KEY  (`branchcode`,`categorycode`)
-                                       )",
-       cities                  => "(`cityid` int auto_increment,
-                                               `city_name` char(100) NOT NULL,
-                                               `city_zipcode` char(20),
-                                               PRIMARY KEY (`cityid`)
-                                       )",
-       roadtype                        => "(`roadtypeid` int auto_increment,
-                                               `road_type` char(100) NOT NULL,
-                                               PRIMARY KEY (`roadtypeid`)
-                                       )",
-
-       labels                     => "(
-                               labelid int(11) NOT NULL auto_increment,
-                               itemnumber varchar(100) NOT NULL default '',
-                               timestamp timestamp(14) NOT NULL,
-                               PRIMARY KEY  (labelid)
-                               )",
-
-       labels_conf                => "(
-                               id int(4) NOT NULL auto_increment,
-                               barcodetype char(100) default '',
-                               title tinyint(1) default '0',
-                               isbn tinyint(1) default '0',
-                               itemtype tinyint(1) default '0',
-                               barcode tinyint(1) default '0',
-                               dewey tinyint(1) default '0',
-                               class tinyint(1) default '0',
-                               author tinyint(1) default '0',
-                               papertype char(100) default '',
-                               startrow int(2) default NULL,
-                               PRIMARY KEY  (id)
-                               )",
+    action_logs     => "(
+                    `timestamp` TIMESTAMP NOT NULL ,
+                    `user` INT( 11 ) NOT NULL ,
+                    `module` TEXT default '',
+                    `action` TEXT default '' ,
+                    `object` INT(11) default '' ,
+                    `info` TEXT default '' ,
+                    PRIMARY KEY ( `timestamp` , `user` )
+                )",
+    letter        => "(
+                    module varchar(20) NOT NULL default '',
+                    code varchar(20) NOT NULL default '',
+                    name varchar(100) NOT NULL default '',
+                    title varchar(200) NOT NULL default '',
+                    content text,
+                    PRIMARY KEY  (module,code)
+                )",
+    alert        =>"(
+                    alertid int(11) NOT NULL auto_increment,
+                    borrowernumber int(11) NOT NULL default '0',
+                    type varchar(10) NOT NULL default '',
+                    externalid varchar(20) NOT NULL default '',
+                    PRIMARY KEY  (alertid),
+                    KEY borrowernumber (borrowernumber),
+                    KEY type (type,externalid)
+                )",
+    opac_news => "(
+                `idnew` int(10) unsigned NOT NULL auto_increment,
+                `title` varchar(250) NOT NULL default '',
+                `new` text NOT NULL,
+                `lang` varchar(4) NOT NULL default '',
+                `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
+                PRIMARY KEY  (`idnew`)
+                )",
+    repeatable_holidays => "(
+                `id` int(11) NOT NULL auto_increment,
+                `branchcode` varchar(4) NOT NULL default '',
+                `weekday` smallint(6) default NULL,
+                `day` smallint(6) default NULL,
+                `month` smallint(6) default NULL,
+                `title` varchar(50) NOT NULL default '',
+                `description` text NOT NULL,
+                PRIMARY KEY  (`id`)
+                )",
+    special_holidays => "(
+                `id` int(11) NOT NULL auto_increment,
+                `branchcode` varchar(4) NOT NULL default '',
+                `day` smallint(6) NOT NULL default '0',
+                `month` smallint(6) NOT NULL default '0',
+                `year` smallint(6) NOT NULL default '0',
+                `isexception` smallint(1) NOT NULL default '1',
+                `title` varchar(50) NOT NULL default '',
+                `description` text NOT NULL,
+                PRIMARY KEY  (`id`)
+                )",
+    overduerules    =>"(`branchcode` varchar(255) NOT NULL default '',
+                    `categorycode` char(2) NOT NULL default '',
+                    `delay1` int(4) default '0',
+                    `letter1` varchar(20) default NULL,
+                    `debarred1` char(1) default '0',
+                    `delay2` int(4) default '0',
+                    `debarred2` char(1) default '0',
+                    `letter2` varchar(20) default NULL,
+                    `delay3` int(4) default '0',
+                    `letter3` varchar(20) default NULL,
+                    `debarred3` int(1) default '0',
+                    PRIMARY KEY  (`branchcode`,`categorycode`)
+                    )",
+    cities            => "(`cityid` int auto_increment,
+                        `city_name` char(100) NOT NULL,
+                        `city_zipcode` char(20),
+                        PRIMARY KEY (`cityid`)
+                    )",
+    roadtype            => "(`roadtypeid` int auto_increment,
+                        `road_type` char(100) NOT NULL,
+                        PRIMARY KEY (`roadtypeid`)
+                    )",
+
+    labels                     => "(
+                labelid int(11) NOT NULL auto_increment,
+                               itemnumber varchar(100) NOT NULL default '',
+                               timestamp timestamp(14) NOT NULL,
+                               PRIMARY KEY  (labelid)
+                               )",
+
+    labels_conf                => "(
+                id int(4) NOT NULL auto_increment,
+                               barcodetype char(100) default '',
+                               title tinyint(1) default '0',
+                               isbn tinyint(1) default '0',
+                               itemtype tinyint(1) default '0',
+                               barcode tinyint(1) default '0',
+                               dewey tinyint(1) default '0',
+                               class tinyint(1) default '0',
+                               author tinyint(1) default '0',
+                               papertype char(100) default '',
+                               startrow int(2) default NULL,
+                               PRIMARY KEY  (id)
+                               )",
        reviews                  => "(
-                               reviewid integer NOT NULL auto_increment,
-                               borrowernumber integer,
-                               biblionumber integer,
-                               review text,
-                               approved tinyint,
-                               datereviewed datetime,
-                               PRIMARY KEY (reviewid)
-                               )",
-       borrowers_to_borrowers  => "(
-                               borrower1 integer,
-                               borrower2 integer
-                               )",
+                            reviewid integer NOT NULL auto_increment,
+                            borrowernumber integer,
+                            biblionumber integer,
+                            review text,
+                            approved tinyint,
+                            datereviewed datetime,
+                            PRIMARY KEY (reviewid)
+                            )",
+    borrowers_to_borrowers  => "(
+                            borrower1 integer,
+                            borrower2 integer
+                            )",
+    subscriptionroutinglist=>"(
+                             routingid integer NOT NULL auto_increment,
+                             borrowernumber integer,
+                             ranking integer,
+                             subscriptionid integer,
+                            PRIMARY KEY (routingid)
+                             )",
+
+    notifys    => "(
+              notify_id int(11) NOT NULL default '0',
+                `borrowernumber` int(11) NOT NULL default '0',
+              `itemnumber` int(11) NOT NULL default '0',
+              `notify_date` date NOT NULL default '0000-00-00',
+                      `notify_send_date` date default NULL,
+                      `notify_level` int(1) NOT NULL default '0',
+                      `method` varchar(20) NOT NULL default ''
+              )",
+
+   charges    => "(
+              `charge_id` varchar(5) NOT NULL default '',
+                `description` text NOT NULL,
+                `amount` decimal(28,6) NOT NULL default '0.000000',
+                          `min` int(4) NOT NULL default '0',
+                `max` int(4) NOT NULL default '0',
+                          `level` int(1) NOT NULL default '0',
+                          PRIMARY KEY  (`charge_id`)
+              )",
+    tags => "(
+        `entry` varchar(255) NOT NULL default '',
+        `weight` bigint(20) NOT NULL default '0',
+         PRIMARY KEY  (`entry`)
+    )
+    ",
+   zebraqueue    => "(
+                `id` int NOT NULL auto_increment,
+                `biblio_auth_number` int NOT NULL,
+                `operation` char(20) NOT NULL,
+                `server` char(20) NOT NULL ,
+                PRIMARY KEY  (`id`)
+              ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci AUTO_INCREMENT=1",
 
 );
 
 my %requirefields = (
-       subscription => { 'letter' => 'char(20) NULL', 'distributedto' => 'text NULL'},
-       itemtypes => { 'imageurl' => 'char(200) NULL'},
-       aqbookfund => { 'branchcode' => 'varchar(4) NULL'},
-       aqbudget => { 'branchcode' => 'varchar(4) NULL'},
-       auth_header => { 'marc' => 'BLOB NOT NULL', 'linkid' => 'BIGINT(20) NULL'},
-       auth_subfield_structure =>{ 'hidden' => 'TINYINT(3) NOT NULL UNSIGNED ZEROFILL', 'kohafield' => 'VARCHAR(45) NOT NULL', 'linkid' =>  'TINYINT(1) NOT NULL UNSIGNED', 'isurl' => 'TINYINT(1) UNSIGNED'},
-        statistics => { 'associatedborrower' => 'integer'},
+    subscription => { 'letter' => 'char(20) NULL', 'distributedto' => 'text NULL', 'firstacquidate'=>'date NOT NULL','irregularity'=>'TEXT NULL default \'\'','numberpattern'=>'TINYINT(3) NULL default 0', 'callnumber'=>'text NULL', 'hemisphere' =>'TINYINT(3) NULL default 0', 'issuesatonce'=>'TINYINT(3) NOT NULL default 1',  'branchcode' =>'varchar(12) NOT NULL default \'\'', 'manualhistory'=>'TINYINT(1) NOT NULL default 0','internalnotes'=>'LONGTEXT NULL default \'\''},
+    itemtypes => { 'imageurl' => 'char(200) NULL'},
+    aqbookfund => { 'branchcode' => 'varchar(4) NULL'},
+    aqbudget => { 'branchcode' => 'varchar(4) NULL'},
+    auth_header => { 'marc' => 'BLOB NOT NULL', 'linkid' => 'BIGINT(20) NULL'},
+    auth_subfield_structure =>{ 'hidden' => 'TINYINT(3) NOT NULL default 0', 'kohafield' => 'VARCHAR(45) NOT NULL', 'linkid' =>  'TINYINT(1) NOT NULL default 0', 'isurl' => 'TINYINT(1)', 'frameworkcode'=>'VARCHAR(8) NOT  NULL'},
+    marc_breeding => { 'isbn' => 'varchar(13) NOT NULL'},
+    serial =>{ 'publisheddate' => 'date', 'claimdate' => 'date', 'itemnumber'=>'text NULL','routingnotes'=>'text NULL',},
+    statistics => { 'associatedborrower' => 'integer'},
+    z3950servers =>{  "name" =>"text",  "description" => "text NOT NULL",
+                    "position" =>"enum('primary','secondary','') NOT NULL default 'primary'",  "icon" =>"text",
+                    "type" =>"enum('zed','opensearch') NOT NULL default 'zed'",
+                    },
+    issues =>{ 'issuedate'=>"date NOT NULL default '0000-00-00'", },
+
 #    tablename        => { 'field' => 'fieldtype' },
 );
 
-my %dropable_table = (
-# tablename => 'tablename',
+# Enter here the table to delete.
+my @TableToDelete = qw(
+    additionalauthors
+    bibliosubject
+    bibliosubtitle
 );
 
 my %uselessfields = (
 # tablename => "field1,field2",
-       borrowers => "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
-       deletedborrowers=> "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
-       );
+    borrowers => "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
+    deletedborrowers=> "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
+    );
 # the other hash contains other actions that can't be done elsewhere. they are done
 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
 
@@ -215,10 +266,10 @@ my %uselessfields = (
 
 my %tabledata = (
 # tablename => [
-#      {       uniquefielrequired => 'fieldname', # the primary key in the table
-#              fieldname => fieldvalue,
-#              fieldname2 => fieldvalue2,
-#      },
+#    {    uniquefielrequired => 'fieldname', # the primary key in the table
+#        fieldname => fieldvalue,
+#        fieldname2 => fieldvalue2,
+#    },
 # ],
     systempreferences => [
         {
@@ -227,14 +278,23 @@ my %tabledata = (
             value               => 'Calendar',
             forceupdate         => { 'explanation' => 1,
                                      'type' => 1},
-            explanation                        => 'How to calculate return dates : Calendar means holidays will be controled, Days means the return date don\'t depend on holidays',
-               type            => 'Choice',
-               options         => 'Calendar|Days'
+            explanation            => 'How to calculate return dates : Calendar means holidays will be controled, Days means the return date don\'t depend on holidays',
+            type        => 'Choice',
+            options        => 'Calendar|Days'
         },
         {
             uniquefieldrequired => 'variable',
-            variable            => 'borrowerMandatoryField',
-            value               => 'zipcode|surname',
+            variable            => 'BorrowersTitles',
+            value               => 'Mr|Mrs|Miss|Ms',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'List all Titles for borrowers',
+            type                => 'free',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'BorrowerMandatoryField',
+            value               => 'cardnumber|surname|address',
             forceupdate         => { 'explanation' => 1,
                                      'type' => 1},
             explanation         => 'List all mandatory fields for borrowers',
@@ -276,7 +336,7 @@ my %tabledata = (
             explanation         => 'Are your patrons members of institutions',
             type                => 'YesNo',
         },
-       {
+    {
             uniquefieldrequired => 'variable',
             variable            => 'ReadingHistory',
             value               => '0',
@@ -285,7 +345,7 @@ my %tabledata = (
             explanation         => 'Allow reading record info retrievable from issues and oldissues tables',
             type                => 'YesNo',
         },
-       {
+    {
             uniquefieldrequired => 'variable',
             variable            => 'IssuingInProcess',
             value               => '0',
@@ -294,7 +354,7 @@ my %tabledata = (
             explanation         => 'Allow no debt alert if the patron is issuing item that accumulate debt',
             type                => 'YesNo',
         },
-       {
+    {
             uniquefieldrequired => 'variable',
             variable            => 'AutomaticItemReturn',
             value               => '1',
@@ -303,7 +363,7 @@ my %tabledata = (
             explanation         => 'This Variable allow or not to return automaticly to his homebranch',
             type                => 'YesNo',
         },
-       {
+    {
             uniquefieldrequired => 'variable',
             variable            => 'reviewson',
             value               => '0',
@@ -312,7 +372,7 @@ my %tabledata = (
             explanation         => 'Allows patrons to submit reviews from the opac',
             type                => 'YesNo',
         },
-       {
+    {
             uniquefieldrequired => 'variable',
             variable            => 'intranet_includes',
             value               => 'includes',
@@ -321,20 +381,602 @@ my %tabledata = (
             explanation         => 'The includes directory you want for specific look of Koha (includes or includes_npl for example)',
             type                => 'Free',
         },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'AutoLocation',
+            value               => '0',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'switch to activate or not Autolocation, if Yes, the Librarian can\'t change his location, it\'s defined by branchip',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'serialsadditems',
+            value               => '0',
+            forceupdate         => {
+                'explanation' => 1,
+                'type' => 1
+            },
+            explanation => 'If set, a new item will be automatically added when receiving an issue',
+            type => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'expandedSearchOption',
+            value               => '0',
+            forceupdate         => {
+                'explanation' => 1,
+                'type' => 1
+            },
+            explanation => 'search among marc field',
+            type => 'YesNo',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'RequestOnOpac',
+            value               => '1',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'option to allow reserves on opac',
+            type                => 'YesNo',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'OpacCloud',
+            value               => '1',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'Enable / Disable cloud link on OPAC',
+            type                => 'YesNo',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'OpacBrowser',
+            value               => '1',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'Enable/Disable browser link on OPAC (needs to set misc/cronjob/build_browser.pl)',
+            type                => 'YesNo',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'OpacTopissue',
+            value               => '1',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'Enable / Disable the top issue link on OPAC',
+            type                => 'YesNo',
+        },
+       {
+            uniquefieldrequired => 'variable',
+            variable            => 'OpacAuthorities',
+            value               => '1',
+            forceupdate         => { 'explanation' => 1,
+                                     'type' => 1},
+            explanation         => 'Enable / Disable the search authority link on OPAC',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'CataloguingLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log cataloguing action.',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'BorrowersLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log borrowers edition/creation/deletion...',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'SubscriptionLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log Subscription action',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'IssueLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log issue.',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'ReturnLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log the circulation return',
+            type                => 'YesNo',
+        },
+        {   
+            uniquefieldrequired => 'variable',
+            variable            => 'LetterLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log all the letter sent',
+            type                => 'YesNo',
+        },
+        {
+            uniquefieldrequired => 'variable',
+            variable            => 'FinesLog',
+            value               => '0',
+            forceupdate         => {'explanation' => 1, 'type' => 1},
+            explanation         => 'Active this if you want to log fines',
+            type                => 'YesNo',
+        },
     ],
-
+    userflags => [
+        {
+            uniquefieldrequired => 'bit',
+            bit                 => '14',
+            flag                => 'editauthorities',
+            flagdesc            => 'allow to edit authorities',
+            defaulton           => '0',
+        },
+        {
+            uniquefieldrequired => 'bit',
+            bit                 => '15',
+            flag                 => 'serials',
+            flagdesc            => 'allow to manage serials subscriptions',
+            defaulton           => '0',
+        },
+        {
+            uniquefieldrequired => 'bit',
+            bit                 => '16',
+            flag                 => 'reports',
+            flagdesc            => 'allow to access to the reports module',
+            defaulton           => '0',
+        },
+    ],
+    authorised_values => [
+        {
+            uniquefieldrequired => 'id',
+            category            => 'SUGGEST',
+            authorised_value    => 'Not enoug budget',
+            lib                 => 'This book it too much expensive',
+        }
+    ]
 );
 
 my %fielddefinitions = (
 # fieldname => [
-#      {                 field => 'fieldname',
+#    {          field => 'fieldname',
 #             type    => 'fieldtype',
 #             null    => '',
 #             key     => '',
 #             default => ''
 #         },
 #     ],
-       serial => [
+    aqbasket =>  [
+        {
+            field    => 'booksellerid',
+            type    => 'int(11)',
+            null    => 'NOT NULL',
+            key        => '',
+            default    => '1',
+            extra    => '',
+        },
+    ],
+    aqbooksellers =>  [
+        {
+            field    => 'id',
+            type    => 'int(11)',
+            null    => 'NOT NULL',
+            key        => '',
+            default    => '',
+            extra    => 'auto_increment',
+        },
+        {
+            field    => 'listprice',
+            type    => 'varchar(10)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'invoiceprice',
+            type    => 'varchar(10)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+    ],
+    
+    accountlines =>  [
+        {
+            field    => 'notify_id',
+            type    => 'int(11)',
+            null    => 'NOT NULL',
+            key        => '',
+            default    => '0',
+            extra    => '',
+        },
+        {
+            field    => 'notify_level',
+            type    => 'int(2)',
+            null    => 'NOT NULL',
+            key        => '',
+            default    => '0',
+            extra    => '',
+        },
+    
+    ],
+    
+    borrowers => [
+        {    field => 'firstname',
+             type => 'text',
+             null => 'NULL',
+         },
+        {    field => 'initials',
+             type => 'text',
+             null => 'NULL',
+         },
+        {    field => 'B_email',
+             type => 'text',
+             null => 'NULL',
+             after => 'B_zipcode',
+         },
+         {
+            field => 'streetnumber', # street number (hidden if streettable table is empty)
+            type => 'char(10)',
+            null => 'NULL',
+            after => 'initials',
+        },
+        {
+            field => 'streettype', # street table, list builded from a system table
+            type => 'char(50)',
+            null => 'NULL',
+            after => 'streetnumber',
+        },
+        {    field => 'phone',
+             type => 'text',
+             null => 'NULL',
+         },
+        {
+            field => 'B_streetnumber', # street number (hidden if streettable table is empty)
+            type => 'char(10)',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'B_streettype', # street table, list builded from a system table
+            type => 'char(50)',
+            null => 'NULL',
+            after => 'B_streetnumber',
+        },
+        {
+            field => 'phonepro',
+            type => 'text',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'address2', # complement address
+            type => 'text',
+            null => 'NULL',
+            after => 'address',
+        },
+        {
+            field => 'emailpro',
+            type => 'text',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'contactfirstname', # contact's firstname
+            type => 'text',
+            null => 'NULL',
+            after => 'contactname',
+        },
+        {
+            field => 'contacttitle', # contact's title
+            type => 'text',
+            null => 'NULL',
+            after => 'contactfirstname',
+        },
+        {
+            field => 'branchcode',
+            type  => 'varchar(10)',
+            null  => 'NOT NULL',
+            default    => '',
+            extra => '',
+        },
+        {
+            field => 'categorycode',
+            type  => 'varchar(10)',
+            null  => 'NOT NULL',
+            default    => '',
+            extra => '',
+        }
+    ],
+    
+    biblioitems =>  [
+        {
+            field    => 'lcsort',
+            type    => 'varchar(25)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'ccode',
+            type    => 'varchar(4)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+    ],
+    branches =>  [
+        {
+            field    => 'branchip',
+            type    => 'varchar(15)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'branchprinter',
+            type    => 'varchar(100)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field   => 'branchcode',
+            type    => 'varchar(10)',
+            null    => 'NOT NULL',
+            default => '',
+            extra   => '',
+        }
+    ],
+    branchtransfers =>[
+        {
+            field   => 'frombranch',
+            type    => 'VARCHAR(10)',
+            null    => 'NOT NULL',
+            key     => '',
+            default => '',
+            extra   => '',
+        },
+        {
+            field   => 'tobranch',
+            type    => 'VARCHAR(10)',
+            null    => 'NOT NULL',
+            key     => '',
+            default => '',
+        }
+    ],
+    
+    categories =>  [
+        {
+            field    => 'category_type',
+            type    => 'char(1)',
+            null    => 'NOT NULL',
+            key        => '',
+            default    => 'A',
+            extra    => '',
+        },
+        {
+            field   => 'categorycode',
+            type    => 'varchar(10)',
+            null    => 'NOT NULL',
+            key     => 'PRI',
+            default => '',
+            extra   => '',
+        },
+    ],
+    
+    deletedborrowers => [
+        {    field => 'firstname',
+             type => 'text',
+             null => 'NULL',
+         },
+        {    field => 'initials',
+             type => 'text',
+             null => 'NULL',
+         },
+        {    field => 'B_email',
+             type => 'text',
+             null => 'NULL',
+             after => 'B_zipcode',
+         },
+         {
+            field => 'streetnumber', # street number (hidden if streettable table is empty)
+            type => 'char(10)',
+            null => 'NULL',
+            after => 'initials',
+        },
+        {
+            field => 'streettype', # street table, list builded from a system table
+            type => 'char(50)',
+            null => 'NULL',
+            after => 'streetnumber',
+        },
+        {    field => 'phone',
+             type => 'text',
+             null => 'NULL',
+         },
+         {
+            field => 'B_streetnumber', # street number (hidden if streettable table is empty)
+            type => 'char(10)',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'B_streettype', # street table, list builded from a system table
+            type => 'char(50)',
+            null => 'NULL',
+            after => 'B_streetnumber',
+        },
+        {
+            field => 'phonepro',
+            type => 'text',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'address2', # complement address
+            type => 'text',
+            null => 'NULL',
+            after => 'address',
+        },
+        {
+            field => 'emailpro',
+            type => 'text',
+            null => 'NULL',
+            after => 'fax',
+        },
+        {
+            field => 'contactfirstname', # contact's firstname
+            type => 'text',
+            null => 'NULL',
+            after => 'contactname',
+        },
+        {
+            field => 'contacttitle', # contact's title
+            type => 'text',
+            null => 'NULL',
+            after => 'contactfirstname',
+        },
+    ],
+    
+    issues =>  [
+        {
+            field    => 'borrowernumber',
+            type    => 'int(11)',
+            null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'itemnumber',
+            type    => 'int(11)',
+            null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field   => 'branchcode',
+            type    => 'varchar(10)',
+            null    => 'NULL',
+            key     => '',
+            default => '',
+            extra   => '',
+        },
+        {
+            field   => 'issuedate',
+            type    => 'date',
+            null    => '',
+            key     => '',
+            default => '0000-00-00',
+            extra   => '',
+        },
+    ],
+    
+    items => [
+        {
+            field    => 'onloan',
+            type    => 'date',
+            null    => 'NULL',
+            key        => '',
+            default    => '0000-00-00',
+            extra    => '',
+        },
+        {
+            field    => 'cutterextra',
+            type    => 'varchar(45)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'issue_date',
+            type    => 'date',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'holdingbranch',
+            type    => 'varchar(10)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'itype',
+            type    => 'varchar(10)',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+    ],
+    itemtypes => [
+        {
+            field  => 'itemtype',
+            type   => 'varchar(10)',
+            default    => '',
+            null   => 'NOT NULL',
+            key    => 'PRI',
+            extra  => 'UNIQUE',
+        },
+        {
+            field  => 'summary',
+            type   => 'TEXT',
+            null   => 'NULL',
+            key    => '',
+            extra  => '',
+        },
+    ],
+    opac_news => [
+        {
+            field  => 'expirationdate',
+            type   => 'date',
+            null   => 'null',
+            key    => '',
+            extra  => '',
+        },
+        {
+            field   => 'number',
+            type    => 'int(11)',
+            null    => 'NULL',
+            key     => '',
+            default => '0',
+            extra   => '',
+        },
+    ],
+    reserves =>  [
+        {
+            field    => 'waitingdate',
+            type    => 'date',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+    ],
+    serial => [
         {
             field   => 'notes',
             type    => 'TEXT',
@@ -344,754 +986,591 @@ my %fielddefinitions = (
             extra   => ''
         },
     ],
-       aqbasket =>  [
-               {
-                       field   => 'booksellerid',
-                       type    => 'int(11)',
-                       null    => 'NOT NULL',
-                       key             => '',
-                       default => '1',
-                       extra   => '',
-               },
-       ],
-       aqbooksellers =>  [
-               {
-                       field   => 'listprice',
-                       type    => 'varchar(10)',
-                       null    => 'NULL',
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-               {
-                       field   => 'invoiceprice',
-                       type    => 'varchar(10)',
-                       null    => 'NULL',
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-       ],
-       issues =>  [
-               {
-                       field   => 'borrowernumber',
-                       type    => 'int(11)',
-                       null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-               {
-                       field   => 'itemnumber',
-                       type    => 'int(11)',
-                       null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-       ],
-       borrowers => [
-               {       field => 'firstname',
-                       type => 'text',
-                       null => 'NULL',
-                },
-               {       field => 'initials',
-                       type => 'text',
-                       null => 'NULL',
-                },
-               {       field => 'B_email',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'B_zipcode',
-                },
-                {
-                       field => 'streetnumber', # street number (hidden if streettable table is empty)
-                       type => 'char(10)',
-                       null => 'NULL',
-                       after => 'initials',
-               },
-               {
-                       field => 'streettype', # street table, list builded from a system table
-                       type => 'char(50)',
-                       null => 'NULL',
-                       after => 'streetnumber',
-               },
-               {       field => 'phone',
-                       type => 'text',
-                       null => 'NULL',
-                },                             
-               {
-                       field => 'B_streetnumber', # street number (hidden if streettable table is empty)
-                       type => 'char(10)',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'B_streettype', # street table, list builded from a system table
-                       type => 'char(50)',
-                       null => 'NULL',
-                       after => 'B_streetnumber',
-               },
-               {
-                       field => 'phonepro',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'address2', # complement address
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'address',
-               },
-               {
-                       field => 'emailpro',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'contactfirstname', # contact's firstname
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'contactname',
-               },
-               {
-                       field => 'contacttitle', # contact's title
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'contactfirstname',
-               },
-       ],
-       
-       deletedborrowers => [
-               {       field => 'firstname',
-                       type => 'text',
-                       null => 'NULL',
-                },
-               {       field => 'initials',
-                       type => 'text',
-                       null => 'NULL',
-                },
-               {       field => 'B_email',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'B_zipcode',
-                },
-                {
-                       field => 'streetnumber', # street number (hidden if streettable table is empty)
-                       type => 'char(10)',
-                       null => 'NULL',
-                       after => 'initials',
-               },
-               {
-                       field => 'streettype', # street table, list builded from a system table
-                       type => 'char(50)',
-                       null => 'NULL',
-                       after => 'streetnumber',
-               },
-               {       field => 'phone',
-                       type => 'text',
-                       null => 'NULL',
-                },             
-                {
-                       field => 'B_streetnumber', # street number (hidden if streettable table is empty)
-                       type => 'char(10)',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'B_streettype', # street table, list builded from a system table
-                       type => 'char(50)',
-                       null => 'NULL',
-                       after => 'B_streetnumber',
-               },
-               {
-                       field => 'phonepro',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'address2', # complement address
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'address',
-               },
-               {
-                       field => 'emailpro',
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'fax',
-               },
-               {
-                       field => 'contactfirstname', # contact's firstname
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'contactname',
-               },
-               {
-                       field => 'contacttitle', # contact's title
-                       type => 'text',
-                       null => 'NULL',
-                       after => 'contactfirstname',
-               },
-       ],
-       
-       branches =>  [
-               {
-                       field   => 'branchip',
-                       type    => 'varchar(15)',
-                       null    => 'NULL',
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-               {
-                       field   => 'branchprinter',
-                       type    => 'varchar(100)',
-                       null    => 'NULL',
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-       ],
-       categories =>  [
-               {
-                       field   => 'category_type',
-                       type    => 'char(1)',
-                       null    => 'NOT NULL',
-                       key             => '',
-                       default => 'A',
-                       extra   => '',
-               },
-       ],
-       reserves =>  [
-               {
-                       field   => 'waitingdate',
-                       type    => 'date',
-                       null    => 'NULL',
-                       key             => '',
-                       default => '',
-                       extra   => '',
-               },
-       ],
-);
-
-my %indexes = (
-#      table => [
-#              {       indexname => 'index detail'
-#              }
-#      ],
-       shelfcontents => [
-               {       indexname => 'shelfnumber',
-                       content => 'shelfnumber',
-               },
-               {       indexname => 'itemnumber',
-                       content => 'itemnumber',
-               }
-       ],
-       bibliosubject => [
-               {       indexname => 'biblionumber',
-                       content => 'biblionumber',
-               }
-       ],
-       items => [
-               {       indexname => 'homebranch',
-                       content => 'homebranch',
-               },
-               {       indexname => 'holdingbranch',
-                       content => 'holdingbranch',
-               }
-       ],
-       aqbooksellers => [
-               {       indexname => 'PRIMARY',
-                       content => 'id',
-                       type => 'PRIMARY',
-               }
-       ],
-       aqbasket => [
-               {       indexname => 'booksellerid',
-                       content => 'booksellerid',
-               },
-       ],
-       aqorders => [
-               {       indexname => 'basketno',
-                       content => 'basketno',
-               },
-       ],
-       aqorderbreakdown => [
-               {       indexname => 'ordernumber',
-                       content => 'ordernumber',
-               },
-               {       indexname => 'bookfundid',
-                       content => 'bookfundid',
-               },
-       ],
-       currency => [
-               {       indexname => 'PRIMARY',
-                       content => 'currency',
-                       type => 'PRIMARY',
-               }
-       ],
-);
-
-my %foreign_keys = (
-#      table => [
-#              {       key => 'the key in table' (must be indexed)
-#                      foreigntable => 'the foreigntable name', # (the parent)
-#                      foreignkey => 'the foreign key column(s)' # (in the parent)
-#                      onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
-#                      onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
-#              }
-#      ],
-       shelfcontents => [
-               {       key => 'shelfnumber',
-                       foreigntable => 'bookshelf',
-                       foreignkey => 'shelfnumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemnumber',
-                       foreigntable => 'items',
-                       foreignkey => 'itemnumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       # onDelete is RESTRICT on reference tables (branches, itemtype) as we don't want items to be 
-       # easily deleted, but branches/itemtype not too easy to empty...
-       biblioitems => [
-               {       key => 'biblionumber',
-                       foreigntable => 'biblio',
-                       foreignkey => 'biblionumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemtype',
-                       foreigntable => 'itemtypes',
-                       foreignkey => 'itemtype',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'RESTRICT',
-               },
-       ],
-       items => [
-               {       key => 'biblioitemnumber',
-                       foreigntable => 'biblioitems',
-                       foreignkey => 'biblioitemnumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'homebranch',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'RESTRICT',
-               },
-               {       key => 'holdingbranch',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'RESTRICT',
-               },
-       ],
-       additionalauthors => [
-               {       key => 'biblionumber',
-                       foreigntable => 'biblio',
-                       foreignkey => 'biblionumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       bibliosubject => [
-               {       key => 'biblionumber',
-                       foreigntable => 'biblio',
-                       foreignkey => 'biblionumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       aqbasket => [
-               {       key => 'booksellerid',
-                       foreigntable => 'aqbooksellers',
-                       foreignkey => 'id',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'RESTRICT',
-               },
-       ],
-       aqorders => [
-               {       key => 'basketno',
-                       foreigntable => 'aqbasket',
-                       foreignkey => 'basketno',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'biblionumber',
-                       foreigntable => 'biblio',
-                       foreignkey => 'biblionumber',
-                       onUpdate => 'SET NULL',
-                       onDelete => 'SET NULL',
-               },
-       ],
-       aqbooksellers => [
-               {       key => 'listprice',
-                       foreigntable => 'currency',
-                       foreignkey => 'currency',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'invoiceprice',
-                       foreigntable => 'currency',
-                       foreignkey => 'currency',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       aqorderbreakdown => [
-               {       key => 'ordernumber',
-                       foreigntable => 'aqorders',
-                       foreignkey => 'ordernumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'bookfundid',
-                       foreigntable => 'aqbookfund',
-                       foreignkey => 'bookfundid',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       branchtransfers => [
-               {       key => 'frombranch',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'tobranch',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemnumber',
-                       foreigntable => 'items',
-                       foreignkey => 'itemnumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       issuingrules => [
-               {       key => 'categorycode',
-                       foreigntable => 'categories',
-                       foreignkey => 'categorycode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemtype',
-                       foreigntable => 'itemtypes',
-                       foreignkey => 'itemtype',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       issues => [     # constraint is SET NULL : when a borrower or an item is deleted, we keep the issuing record
-       # for stat purposes
-               {       key => 'borrowernumber',
-                       foreigntable => 'borrowers',
-                       foreignkey => 'borrowernumber',
-                       onUpdate => 'SET NULL',
-                       onDelete => 'SET NULL',
-               },
-               {       key => 'itemnumber',
-                       foreigntable => 'items',
-                       foreignkey => 'itemnumber',
-                       onUpdate => 'SET NULL',
-                       onDelete => 'SET NULL',
-               },
-       ],
-       reserves => [
-               {       key => 'borrowernumber',
-                       foreigntable => 'borrowers',
-                       foreignkey => 'borrowernumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'biblionumber',
-                       foreigntable => 'biblio',
-                       foreignkey => 'biblionumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemnumber',
-                       foreigntable => 'items',
-                       foreignkey => 'itemnumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'branchcode',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       borrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
-       # but prevent deleting a branch as soon as it has 1 borrower !
-               {       key => 'categorycode',
-                       foreigntable => 'categories',
-                       foreignkey => 'categorycode',
-                       onUpdate => 'RESTRICT',
-                       onDelete => 'RESTRICT',
-               },
-               {       key => 'branchcode',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'RESTRICT',
-                       onDelete => 'RESTRICT',
-               },
-       ],
-       deletedborrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
-       # but prevent deleting a branch as soon as it has 1 borrower !
-               {       key => 'categorycode',
-                       foreigntable => 'categories',
-                       foreignkey => 'categorycode',
-                       onUpdate => 'RESTRICT',
-                       onDelete => 'RESTRICT',
-               },
-               {       key => 'branchcode',
-                       foreigntable => 'branches',
-                       foreignkey => 'branchcode',
-                       onUpdate => 'RESTRICT',
-                       onDelete => 'RESTRICT',
-               },
-       ],
-       accountlines => [
-               {       key => 'borrowernumber',
-                       foreigntable => 'borrowers',
-                       foreignkey => 'borrowernumber',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-               {       key => 'itemnumber',
-                       foreigntable => 'items',
-                       foreignkey => 'itemnumber',
-                       onUpdate => 'SET NULL',
-                       onDelete => 'SET NULL',
-               },
-       ],
-       auth_tag_structure => [
-               {       key => 'authtypecode',
-                       foreigntable => 'auth_types',
-                       foreignkey => 'authtypecode',
-                       onUpdate => 'CASCADE',
-                       onDelete => 'CASCADE',
-               },
-       ],
-       # FIXME : don't constraint auth_*_table and auth_word, as they may be replaced by zebra
-);
-
-
-# column changes
-my %column_change = (
-       # table
-       borrowers => [
-                               {
-                                       from => 'emailaddress',
-                                       to => 'email',
-                                       after => 'city',
-                               },
-                               {
-                                       from => 'streetaddress',
-                                       to => 'address',
-                                       after => 'initials',
-                               },
-                               {
-                                       from => 'faxnumber',
-                                       to => 'fax',
-                                       after => 'phone',
-                               },
-                               {
-                                       from => 'textmessaging',
-                                       to => 'opacnote',
-                                       after => 'userid',
-                               },
-                               {
-                                       from => 'altnotes',
-                                       to => 'contactnote',
-                                       after => 'opacnote',
-                               },
-                               {
-                                       from => 'physstreet',
-                                       to => 'B_address',
-                                       after => 'fax',
-                               },
-                               {
-                                       from => 'streetcity',
-                                       to => 'B_city',
-                                       after => 'B_address',
-                               },
-                               {
-                                       from => 'phoneday',
-                                       to => 'mobile',
-                                       after => 'phone',
-                               },
-                               {
-                                       from => 'zipcode',
-                                       to => 'zipcode',
-                                       after => 'city',
-                               },
-                               {
-                                       from => 'homezipcode',
-                                       to => 'B_zipcode',
-                                       after => 'B_city',
-                               },
-                               {
-                                       from => 'altphone',
-                                       to => 'B_phone',
-                                       after => 'B_zipcode',
-                               },
-                               {
-                                       from => 'expiry',
-                                       to => 'dateexpiry',
-                                       after => 'dateenrolled',
-                               },
-                               {
-                                       from => 'guarantor',
-                                       to => 'guarantorid',
-                                       after => 'contactname',
-                               },
-                               {
-                                       from => 'textmessaging',
-                                       to => 'opacnotes',
-                                       after => 'flags',
-                               },
-                               {
-                                       from => 'altnotes',
-                                       to => 'contactnotes',
-                                       after => 'opacnotes',
-                               },
-                               {
-                                       from => 'altrelationship',
-                                       to => 'relationship',
-                                       after => 'borrowernotes',
-                               },
-                       ],
+    shelfcontents => [
+        {
+            field => 'dateadded',
+            type => 'timestamp',
+            null    => 'NULL',
+        },
+    ],
+    systempreferences =>  [
+        {
+            field    => 'value',
+            type    => 'text',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+        {
+            field    => 'explanation',
+            type    => 'text',
+            null    => 'NULL',
+            key        => '',
+            default    => '',
+            extra    => '',
+        },
+    ],
+    suggestions => [
+        {
+            field   => 'reason',
+            type    => 'text',
+            null    => 'NULL',
+            key     => ''  ,
+            default => '',
+            extra   =>    '',
+        }
+    ],
+);
+
+my %indexes = (
+#    table => [
+#         {    indexname => 'index detail'
+#         }
+#    ],
+    aqbooksellers => [
+        {    indexname => 'PRIMARY',
+            content => 'id',
+            type => 'PRI',
+        }
+    ],
+    aqbasket => [
+        {    indexname => 'booksellerid',
+            content => 'booksellerid',
+        },
+    ],
+    aqorders => [
+        {    indexname => 'basketno',
+            content => 'basketno',
+        },
+    ],
+    aqorderbreakdown => [
+        {    indexname => 'ordernumber',
+            content => 'ordernumber',
+        },
+        {    indexname => 'bookfundid',
+            content => 'bookfundid',
+        },
+    ],
+    biblioitems => [
+        {    indexname => 'isbn',
+            content => 'isbn',
+        },
+        {    indexname => 'publishercode',
+            content => 'publishercode',
+        },
+    ],
+    branches => [
+        {
+            indexname => 'branchcode',
+            content   => 'branchcode',
+    
+        }
+    ],
+    currency => [
+        {    indexname => 'PRIMARY',
+            content => 'currency',
+            type => 'PRI',
+        }
+    ],
+    categories => [
+        {
+            indexname => 'categorycode',
+            content   => 'categorycode',
+        }
+    ],
+    items => [
+        {    indexname => 'homebranch',
+            content => 'homebranch',
+        },
+        {    indexname => 'holdingbranch',
+            content => 'holdingbranch',
+        }
+    ],
+    itemtypes => [
+        {
+            indexname => 'itemtype',
+            content   => 'itemtype',
+        }
+    ],
+    shelfcontents => [
+        {    indexname => 'shelfnumber',
+            content => 'shelfnumber',
+        },
+        {    indexname => 'itemnumber',
+            content => 'itemnumber',
+        }
+    ],
+);
+
+my %foreign_keys = (
+#    table => [
+#         {    key => 'the key in table' (must be indexed)
+#            foreigntable => 'the foreigntable name', # (the parent)
+#            foreignkey => 'the foreign key column(s)' # (in the parent)
+#            onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
+#            onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
+#         }
+#    ],
+    shelfcontents => [
+        {    key => 'shelfnumber',
+            foreigntable => 'bookshelf',
+            foreignkey => 'shelfnumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemnumber',
+            foreigntable => 'items',
+            foreignkey => 'itemnumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    # onDelete is RESTRICT on reference tables (branches, itemtype) as we don't want items to be
+    # easily deleted, but branches/itemtype not too easy to empty...
+    biblioitems => [
+        {    key => 'biblionumber',
+            foreigntable => 'biblio',
+            foreignkey => 'biblionumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemtype',
+            foreigntable => 'itemtypes',
+            foreignkey => 'itemtype',
+            onUpdate => 'CASCADE',
+            onDelete => 'RESTRICT',
+        },
+    ],
+    items => [
+        {    key => 'biblioitemnumber',
+            foreigntable => 'biblioitems',
+            foreignkey => 'biblioitemnumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'homebranch',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'CASCADE',
+            onDelete => 'RESTRICT',
+        },
+        {    key => 'holdingbranch',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'CASCADE',
+            onDelete => 'RESTRICT',
+        },
+    ],
+    aqbasket => [
+        {    key => 'booksellerid',
+            foreigntable => 'aqbooksellers',
+            foreignkey => 'id',
+            onUpdate => 'CASCADE',
+            onDelete => 'RESTRICT',
+        },
+    ],
+    aqorders => [
+        {    key => 'basketno',
+            foreigntable => 'aqbasket',
+            foreignkey => 'basketno',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'biblionumber',
+            foreigntable => 'biblio',
+            foreignkey => 'biblionumber',
+            onUpdate => 'SET NULL',
+            onDelete => 'SET NULL',
+        },
+    ],
+    aqbooksellers => [
+        {    key => 'listprice',
+            foreigntable => 'currency',
+            foreignkey => 'currency',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'invoiceprice',
+            foreigntable => 'currency',
+            foreignkey => 'currency',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    aqorderbreakdown => [
+        {    key => 'ordernumber',
+            foreigntable => 'aqorders',
+            foreignkey => 'ordernumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'bookfundid',
+            foreigntable => 'aqbookfund',
+            foreignkey => 'bookfundid',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    branchtransfers => [
+        {    key => 'frombranch',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'tobranch',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemnumber',
+            foreigntable => 'items',
+            foreignkey => 'itemnumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    issuingrules => [
+        {    key => 'categorycode',
+            foreigntable => 'categories',
+            foreignkey => 'categorycode',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemtype',
+            foreigntable => 'itemtypes',
+            foreignkey => 'itemtype',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    issues => [    # constraint is SET NULL : when a borrower or an item is deleted, we keep the issuing record
+    # for stat purposes
+        {    key => 'borrowernumber',
+            foreigntable => 'borrowers',
+            foreignkey => 'borrowernumber',
+            onUpdate => 'SET NULL',
+            onDelete => 'SET NULL',
+        },
+        {    key => 'itemnumber',
+            foreigntable => 'items',
+            foreignkey => 'itemnumber',
+            onUpdate => 'SET NULL',
+            onDelete => 'SET NULL',
+        },
+    ],
+    reserves => [
+        {    key => 'borrowernumber',
+            foreigntable => 'borrowers',
+            foreignkey => 'borrowernumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'biblionumber',
+            foreigntable => 'biblio',
+            foreignkey => 'biblionumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemnumber',
+            foreigntable => 'items',
+            foreignkey => 'itemnumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'branchcode',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    borrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
+    # but prevent deleting a branch as soon as it has 1 borrower !
+        {    key => 'categorycode',
+            foreigntable => 'categories',
+            foreignkey => 'categorycode',
+            onUpdate => 'RESTRICT',
+            onDelete => 'RESTRICT',
+        },
+        {    key => 'branchcode',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'RESTRICT',
+            onDelete => 'RESTRICT',
+        },
+    ],
+    deletedborrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
+    # but prevent deleting a branch as soon as it has 1 borrower !
+        {    key => 'categorycode',
+            foreigntable => 'categories',
+            foreignkey => 'categorycode',
+            onUpdate => 'RESTRICT',
+            onDelete => 'RESTRICT',
+        },
+        {    key => 'branchcode',
+            foreigntable => 'branches',
+            foreignkey => 'branchcode',
+            onUpdate => 'RESTRICT',
+            onDelete => 'RESTRICT',
+        },
+    ],
+    accountlines => [
+        {    key => 'borrowernumber',
+            foreigntable => 'borrowers',
+            foreignkey => 'borrowernumber',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+        {    key => 'itemnumber',
+            foreigntable => 'items',
+            foreignkey => 'itemnumber',
+            onUpdate => 'SET NULL',
+            onDelete => 'SET NULL',
+        },
+    ],
+    auth_tag_structure => [
+        {    key => 'authtypecode',
+            foreigntable => 'auth_types',
+            foreignkey => 'authtypecode',
+            onUpdate => 'CASCADE',
+            onDelete => 'CASCADE',
+        },
+    ],
+    # FIXME : don't constraint auth_*_table and auth_word, as they may be replaced by zebra
+);
+
+
+# column changes
+my %column_change = (
+    # table
+    borrowers => [
+                {
+                    from => 'emailaddress',
+                    to => 'email',
+                    after => 'city',
+                },
+                {
+                    from => 'streetaddress',
+                    to => 'address',
+                    after => 'initials',
+                },
+                {
+                    from => 'faxnumber',
+                    to => 'fax',
+                    after => 'phone',
+                },
+                {
+                    from => 'textmessaging',
+                    to => 'opacnote',
+                    after => 'userid',
+                },
+                {
+                    from => 'altnotes',
+                    to => 'contactnote',
+                    after => 'opacnote',
+                },
+                {
+                    from => 'physstreet',
+                    to => 'B_address',
+                    after => 'fax',
+                },
+                {
+                    from => 'streetcity',
+                    to => 'B_city',
+                    after => 'B_address',
+                },
+                {
+                    from => 'phoneday',
+                    to => 'mobile',
+                    after => 'phone',
+                },
+                {
+                    from => 'zipcode',
+                    to => 'zipcode',
+                    after => 'city',
+                },
+                {
+                    from => 'homezipcode',
+                    to => 'B_zipcode',
+                    after => 'B_city',
+                },
+                {
+                    from => 'altphone',
+                    to => 'B_phone',
+                    after => 'B_zipcode',
+                },
+                {
+                    from => 'expiry',
+                    to => 'dateexpiry',
+                    after => 'dateenrolled',
+                },
+                {
+                    from => 'guarantor',
+                    to => 'guarantorid',
+                    after => 'contactname',
+                },
+                {
+                    from => 'altrelationship',
+                    to => 'relationship',
+                    after => 'borrowernotes',
+                },
+            ],
+
+    deletedborrowers => [
+                {
+                    from => 'emailaddress',
+                    to => 'email',
+                    after => 'city',
+                },
+                {
+                    from => 'streetaddress',
+                    to => 'address',
+                    after => 'initials',
+                },
+                {
+                    from => 'faxnumber',
+                    to => 'fax',
+                    after => 'phone',
+                },
+                {
+                    from => 'textmessaging',
+                    to => 'opacnote',
+                    after => 'userid',
+                },
+                {
+                    from => 'altnotes',
+                    to => 'contactnote',
+                    after => 'opacnote',
+                },
+                {
+                    from => 'physstreet',
+                    to => 'B_address',
+                    after => 'fax',
+                },
+                {
+                    from => 'streetcity',
+                    to => 'B_city',
+                    after => 'B_address',
+                },
+                {
+                    from => 'phoneday',
+                    to => 'mobile',
+                    after => 'phone',
+                },
+                {
+                    from => 'zipcode',
+                    to => 'zipcode',
+                    after => 'city',
+                },
+                {
+                    from => 'homezipcode',
+                    to => 'B_zipcode',
+                    after => 'B_city',
+                },
+                {
+                    from => 'altphone',
+                    to => 'B_phone',
+                    after => 'B_zipcode',
+                },
+                {
+                    from => 'expiry',
+                    to => 'dateexpiry',
+                    after => 'dateenrolled',
+                },
+                {
+                    from => 'guarantor',
+                    to => 'guarantorid',
+                    after => 'contactname',
+                },
+                {
+                    from => 'altrelationship',
+                    to => 'relationship',
+                    after => 'borrowernotes',
+                },
+            ],
+        );
+    
+
+# MOVE all tables TO UTF-8 and innoDB
+$sth = $dbh->prepare("show table status");
+$sth->execute;
+while ( my $table = $sth->fetchrow_hashref ) {
+     if ($table->{Engine} ne 'InnoDB') {
+         $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
+         print "moving $table->{Name} to InnoDB\n";
+     }
+    next if $table->{Name} eq 'marc_word';
+    next if $table->{Name} eq 'marc_subfield_table';
+    next if $table->{Name} eq 'auth_word';
+    next if $table->{Name} eq 'auth_subfield_table';
+    unless ($table->{Collation} =~ /^utf8/) {
+         print "moving $table->{Name} to utf8\n";
+        $dbh->do("ALTER TABLE $table->{Name} CONVERT TO CHARACTER SET utf8");
+        $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
+        # FIXME : maybe a ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 would be better, def char set seems to work fine. If any problem encountered, let's try with convert !
+    } else {
+    }
+}
 
-       deletedborrowers => [
-                               {
-                                       from => 'emailaddress',
-                                       to => 'email',
-                                       after => 'city',
-                               },
-                               {
-                                       from => 'streetaddress',
-                                       to => 'address',
-                                       after => 'initials',
-                               },
-                               {
-                                       from => 'faxnumber',
-                                       to => 'fax',
-                                       after => 'phone',
-                               },
-                               {
-                                       from => 'textmessaging',
-                                       to => 'opacnote',
-                                       after => 'userid',
-                               },
-                               {
-                                       from => 'altnotes',
-                                       to => 'contactnote',
-                                       after => 'opacnote',
-                               },
-                               {
-                                       from => 'physstreet',
-                                       to => 'B_address',
-                                       after => 'fax',
-                               },
-                               {
-                                       from => 'streetcity',
-                                       to => 'B_city',
-                                       after => 'B_address',
-                               },
-                               {
-                                       from => 'phoneday',
-                                       to => 'mobile',
-                                       after => 'phone',
-                               },
-                               {
-                                       from => 'zipcode',
-                                       to => 'zipcode',
-                                       after => 'city',
-                               },
-                               {
-                                       from => 'homezipcode',
-                                       to => 'B_zipcode',
-                                       after => 'B_city',
-                               },
-                               {
-                                       from => 'altphone',
-                                       to => 'B_phone',
-                                       after => 'B_zipcode',
-                               },
-                               {
-                                       from => 'expiry',
-                                       to => 'dateexpiry',
-                                       after => 'dateenrolled',
-                               },
-                               {
-                                       from => 'guarantor',
-                                       to => 'guarantorid',
-                                       after => 'contactname',
-                               },
-                               {
-                                       from => 'textmessaging',
-                                       to => 'opacnotes',
-                                       after => 'flags',
-                               },
-                               {
-                                       from => 'altnotes',
-                                       to => 'contactnotes',
-                                       after => 'opacnotes',
-                               },
-                               {
-                                       from => 'altrelationship',
-                                       to => 'relationship',
-                                       after => 'borrowernotes',
-                               },
-                       ],
 
-               );
-               
 foreach my $table (keys %column_change) {
-       $sth = $dbh->prepare("show columns from $table");
-       $sth->execute();
-       undef %types;
-       while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
-       {
-               $types{$column}->{type} ="$type";
-               $types{$column}->{null} = "$null";
-               $types{$column}->{key} = "$key";
-               $types{$column}->{default} = "$default";
-               $types{$column}->{extra} = "$extra";
-       }    # while
-       my $tablerows = $column_change{$table};
-       foreach my $row ( @$tablerows ) {
-               if ($types{$row->{from}}->{type}) {
-                       print "altering $table $row->{from} to $row->{to}\n";
-                       # ALTER TABLE `borrowers` CHANGE `faxnumber` `fax` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL 
-#                      alter table `borrowers` change `faxnumber` `fax` type text  null after phone
-                       my $sql = 
-                               "alter table `$table` change `$row->{from}` `$row->{to}` $types{$row->{from}}->{type} ".
-                               ($types{$row->{from}}->{null} eq 'YES'?" NULL":" NOT NULL").
-                               ($types{$row->{from}}->{default}?" default ".$types{$row->{from}}->{default}:"").
-                               "$types{$row->{from}}->{extra} after $row->{after} ";
-#                      print "$sql";
-                       $dbh->do($sql);
-               }
-       }
+    $sth = $dbh->prepare("show columns from $table");
+    $sth->execute();
+    undef %types;
+    while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
+    {
+        $types{$column}->{type} ="$type";
+        $types{$column}->{null} = "$null";
+        $types{$column}->{key} = "$key";
+        $types{$column}->{default} = "$default";
+        $types{$column}->{extra} = "$extra";
+    }    # while
+    my $tablerows = $column_change{$table};
+    foreach my $row ( @$tablerows ) {
+        if ($types{$row->{from}}->{type}) {
+            print "altering $table $row->{from} to $row->{to}\n";
+            # ALTER TABLE `borrowers` CHANGE `faxnumber` `fax` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
+#             alter table `borrowers` change `faxnumber` `fax` type text  null after phone
+            my $sql =
+                "alter table `$table` change `$row->{from}` `$row->{to}` $types{$row->{from}}->{type} ".
+                ($types{$row->{from}}->{null} eq 'YES'?" NULL":" NOT NULL").
+                ($types{$row->{from}}->{default}?" default ".$types{$row->{from}}->{default}:"").
+                "$types{$row->{from}}->{extra} after $row->{after} ";
+#             print "$sql";
+            $dbh->do($sql);
+        }
+    }
 }
 
+# Enter here the field you want to delete from DB.
+# FIXME :: there is a %uselessfield before which seems doing the same things.
+my %fieldtodelete = (
+    # tablename => [fieldname1,fieldname2,...]
+
+); # %fielddelete
+
+print "removing some unused fields...\n";
+foreach my $table ( keys %fieldtodelete ) {
+    foreach my $field ( @{$fieldtodelete{$table}} ){
+        print "removing ".$field." from ".$table;
+        my $sth = $dbh->prepare("ALTER TABLE $table DROP $field");
+        $sth->execute;
+        if ( $sth->err ) {
+            print "Error : $sth->errstr \n";
+        }
+    }
+}
+
+# Enter here the line you want to remove from DB.
+my %linetodelete = (
+    # table name => where clause.
+    userflags => "bit = 8", # delete the 'reserveforself' flags
+    
+); # %linetodelete
+
 #-------------------
 # Initialize
 
@@ -1119,7 +1598,7 @@ while ( my ($table) = $sth->fetchrow ) {
 # Now add any missing tables
 foreach $table ( keys %requiretables ) {
     unless ( $existingtables{$table} ) {
-       print "Adding $table table...\n" unless $silent;
+    print "Adding $table table...\n" unless $silent;
         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
         $sth->execute;
         if ( $sth->err ) {
@@ -1129,17 +1608,6 @@ foreach $table ( keys %requiretables ) {
     }    # unless exists
 }    # foreach
 
-# now drop useless tables
-foreach $table ( keys %dropable_table ) {
-       if ( $existingtables{$table} ) {
-               print "Dropping unused table $table\n" if $debug and not $silent;
-               $dbh->do("drop table $table");
-               if ( $dbh->err ) {
-                       print "Error : $dbh->errstr \n";
-               }
-       }
-}
-
 #---------------------------------
 # Columns
 
@@ -1159,7 +1627,7 @@ foreach $table ( keys %requirefields ) {
             # column doesn't exist
             print "Adding $column field to $table table...\n" unless $silent;
             $query = "alter table $table
-                       add column $column " . $requirefields{$table}->{$column};
+            add column $column " . $requirefields{$table}->{$column};
             print "Execute: $query\n" if $debug;
             my $sti = $dbh->prepare($query);
             $sti->execute;
@@ -1172,100 +1640,128 @@ foreach $table ( keys %requirefields ) {
 }    # foreach table
 
 foreach $table ( keys %fielddefinitions ) {
-       print "Check table $table\n" if $debug;
-       $sth = $dbh->prepare("show columns from $table");
-       $sth->execute();
-       my $definitions;
-       while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
-       {
-               $definitions->{$column}->{type}    = $type;
-               $definitions->{$column}->{null}    = $null;
-               $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
-               $definitions->{$column}->{key}     = $key;
-               $definitions->{$column}->{default} = $default;
-               $definitions->{$column}->{extra}   = $extra;
-       }    # while
-       my $fieldrow = $fielddefinitions{$table};
-       foreach my $row (@$fieldrow) {
-               my $field   = $row->{field};
-               my $type    = $row->{type};
-               my $null    = $row->{null};
-#              $null    = 'YES' if $row->{null} eq 'NULL';
-               my $key     = $row->{key};
-               my $default = $row->{default};
-               my $null    = $row->{null};
-#              $default="''" unless $default;
-               my $extra   = $row->{extra};
-               my $def     = $definitions->{$field};
-               my $after       = ($row->{after}?" after ".$row->{after}:"");
-
-               unless ( $type eq $def->{type}
-                       && $null eq $def->{null}
-                       && $key eq $def->{key}
-                       && $extra eq $def->{extra} )
-               {
-                       if ( $null eq '' ) {
-                               $null = 'NOT NULL';
-                       }
-                       if ( $key eq 'PRI' ) {
-                               $key = 'PRIMARY KEY';
-                       }
-                       unless ( $extra eq 'auto_increment' ) {
-                               $extra = '';
-                       }
-
-                       # if it's a new column use "add", if it's an old one, use "change".
-                       my $action;
-                       if ($definitions->{$field}->{type}) {
-                               $action="change $field"
-                       } else {
-                               $action="add";
-                       }
+    print "Check table $table\n" if $debug;
+    $sth = $dbh->prepare("show columns from $table");
+    $sth->execute();
+    my $definitions;
+    while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
+    {
+        $definitions->{$column}->{type}    = $type;
+        $definitions->{$column}->{null}    = $null;
+        $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
+        $definitions->{$column}->{key}     = $key;
+        $definitions->{$column}->{default} = $default;
+        $definitions->{$column}->{extra}   = $extra;
+    }    # while
+    my $fieldrow = $fielddefinitions{$table};
+    foreach my $row (@$fieldrow) {
+        my $field   = $row->{field};
+        my $type    = $row->{type};
+        my $null    = $row->{null};
+#         $null    = 'YES' if $row->{null} eq 'NULL';
+        my $key     = $row->{key};
+        my $default = $row->{default};
+#         $default="''" unless $default;
+        my $extra   = $row->{extra};
+        my $def     = $definitions->{$field};
+        my $after    = ($row->{after}?" after ".$row->{after}:"");
+
+        unless ( $type eq $def->{type}
+            && $null eq $def->{null}
+            && $key eq $def->{key}
+            && $extra eq $def->{extra} )
+        {
+            if ( $null eq '' ) {
+                $null = 'NOT NULL';
+            }
+            if ( $key eq 'PRI' ) {
+                $key = 'PRIMARY KEY';
+            }
+            unless ( $extra eq 'auto_increment' ) {
+                $extra = '';
+            }
+    
+            # if it's a new column use "add", if it's an old one, use "change".
+            my $action;
+            if ($definitions->{$field}->{type}) {
+                $action="change $field"
+            } else {
+                $action="add";
+            }
 # if it's a primary key, drop the previous pk, before altering the table
-                       my $sth;
-                       if ($key ne 'PRIMARY KEY') {
-                               $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
-                       } else {
-                               $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ? $after");
-                       }
-                       $sth->execute($default);
-                       print "  alter or create $field in $table\n" unless $silent;
-               }
-       }
+            my $sth;
+            if ($key ne 'PRIMARY KEY') {
+#                 warn "alter table $table $action $field $type $null $key $extra default $default $after";
+                $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
+            } else {
+#             warn "alter table $table drop primary key, $action $field $type $null $key $extra default $default $after";
+                 # something strange : for indexes UNIQUE, they are reported as primary key here.
+                 # but if you try to run with drop primary key, it fails.
+                 # thus, we run the query twice, one will fail, one will succeed.
+                 # strange...
+                $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ? $after");
+                $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
+            }
+# ALTER TABLE `borrowers` CHANGE `branchcode` `branchcode` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL 
+            print "  alter or create $field in $table\n" unless $silent;
+            $sth->execute($default);
+        }
+    }
 }
 
-# Populate tables with required data
+print "removing some unused data...\n";
+foreach my $table ( keys %linetodelete ) {
+    foreach my $where ( @{linetodelete{$table}} ){
+        print "DELETE FROM ".$table." where ".$where;
+        print "\n";
+        my $sth = $dbh->prepare("DELETE FROM $table where $where");
+        $sth->execute;
+        if ( $sth->err ) {
+            print "Error : $sth->errstr \n";
+        }
+    }
+}
 
+# Populate tables with required data
 
 # synch table and deletedtable.
 foreach my $table (('borrowers','items','biblio','biblioitems')) {
-       my %deletedborrowers;
-       print "synch'ing $table\n";
-       $sth = $dbh->prepare("show columns from deleted$table");
-       $sth->execute;
-       while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
-               $deletedborrowers{$column}=1;
-       }
-       $sth = $dbh->prepare("show columns from $table");
-       $sth->execute;
-       my $previous;
-       while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
-               unless ($deletedborrowers{$column}) {
-                       my $newcol="alter table deleted$table add $column $type";
-                       if ($null eq 'YES') {
-                               $newcol .= " NULL ";
-                       } else {
-                               $newcol .= " NOT NULL ";
-                       }
-                       $newcol .= "default $default" if $default;
-                       $newcol .= " after $previous" if $previous;
-                       $previous=$column;
-                       print "creating column $column\n";
-                       $dbh->do($newcol);
-               }
-       }
+    my %deletedborrowers;
+    print "synch'ing $table and deleted$table\n";
+    $sth = $dbh->prepare("show columns from deleted$table");
+    $sth->execute;
+    while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
+        $deletedborrowers{$column}=1;
+    }
+    $sth = $dbh->prepare("show columns from $table");
+    $sth->execute;
+    my $previous;
+    while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
+        unless ($deletedborrowers{$column}) {
+            my $newcol="alter table deleted$table add $column $type";
+            if ($null eq 'YES') {
+                $newcol .= " NULL ";
+            } else {
+                $newcol .= " NOT NULL ";
+            }
+            $newcol .= "default ".$dbh->quote($default) if $default;
+            $newcol .= " after $previous" if $previous;
+            $previous=$column;
+            print "creating column $column\n";
+            $dbh->do($newcol);
+        }
+    }
+}
+#
+# update publisheddate 
+#
+$sth = $dbh->prepare("select count(*) from serial where publisheddate is NULL");
+$sth->execute;
+my ($emptypublished) = $sth->fetchrow;
+if ($emptypublished) {
+    print "Updating publisheddate\n";
+    $dbh->do("update serial set publisheddate=planneddate where publisheddate is NULL");
 }
-
 foreach my $table ( keys %tabledata ) {
     print "Checking for data required in table $table...\n" unless $silent;
     my $tablerows = $tabledata{$table};
@@ -1278,36 +1774,37 @@ foreach my $table ( keys %tabledata ) {
 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
         );
         $sth->execute($uniquevalue);
-               if ($sth->rows) {
-                       foreach my $field (keys %$forceupdate) {
-                               if ($forceupdate->{$field}) {
-                                       my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
-                                       $sth->execute($row->{$field}, $uniquevalue);
-                               }
-               }
-               } else {
-                       print "Adding row to $table: " unless $silent;
-                       my @values;
-                       my $fieldlist;
-                       my $placeholders;
-                       foreach my $field ( keys %$row ) {
-                               next if $field eq 'uniquefieldrequired';
-                               next if $field eq 'forceupdate';
-                               my $value = $row->{$field};
-                               push @values, $value;
-                               print "  $field => $value" unless $silent;
-                               $fieldlist .= "$field,";
-                               $placeholders .= "?,";
-                       }
-                       print "\n" unless $silent;
-                       $fieldlist    =~ s/,$//;
-                       $placeholders =~ s/,$//;
-                       my $sth =
-                       $dbh->prepare(
-                               "insert into $table ($fieldlist) values ($placeholders)");
-                       $sth->execute(@values);
-               }
-       }
+        if ($sth->rows) {
+            foreach my $field (keys %$forceupdate) {
+                if ($forceupdate->{$field}) {
+                    my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
+                    $sth->execute($row->{$field}, $uniquevalue);
+                }
+            }
+        } else {
+            print "Adding row to $table: " unless $silent;
+            my @values;
+            my $fieldlist;
+            my $placeholders;
+            foreach my $field ( keys %$row ) {
+                next if $field eq 'uniquefieldrequired';
+                next if $field eq 'forceupdate';
+                my $value = $row->{$field};
+                push @values, $value;
+                print "  $field => $value" unless $silent;
+                $fieldlist .= "$field,";
+                $placeholders .= "?,";
+            }
+            print "\n" unless $silent;
+            $fieldlist    =~ s/,$//;
+            $placeholders =~ s/,$//;
+            print "insert into $table ($fieldlist) values ($placeholders)";
+            my $sth =
+            $dbh->prepare(
+                "insert into $table ($fieldlist) values ($placeholders)");
+            $sth->execute(@values);
+        }
+    }
 }
 
 #
@@ -1315,33 +1812,33 @@ foreach my $table ( keys %tabledata ) {
 #
 print "Checking for index required...\n" unless $silent;
 foreach my $table ( keys %indexes ) {
-       #
-       # read all indexes from $table
-       #
-       $sth = $dbh->prepare("show index from $table");
-       $sth->execute;
-       my %existingindexes;
-       while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
-               $existingindexes{$key_name} = 1;
-       }
-       # read indexes to check
-       my $tablerows = $indexes{$table};
-       foreach my $row (@$tablerows) {
-               my $key_name=$row->{indexname};
-               if ($existingindexes{$key_name} eq 1) {
-#                      print "$key_name existing";
-               } else {
-                       print "\tCreating index $key_name in $table\n";
-                       my $sql;
-                       if ($row->{indexname} eq 'PRIMARY') {
-                               $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
-                       } else {
-                               $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
-                       }
-                       $dbh->do($sql);
+    #
+    # read all indexes from $table
+    #
+    $sth = $dbh->prepare("show index from $table");
+    $sth->execute;
+    my %existingindexes;
+    while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
+        $existingindexes{$key_name} = 1;
+    }
+    # read indexes to check
+    my $tablerows = $indexes{$table};
+    foreach my $row (@$tablerows) {
+        my $key_name=$row->{indexname};
+        if ($existingindexes{$key_name} eq 1) {
+#             print "$key_name existing";
+        } else {
+            print "\tCreating index $key_name in $table\n";
+            my $sql;
+            if ($row->{indexname} eq 'PRIMARY') {
+                $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
+            } else {
+                $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
+            }
+             $dbh->do($sql);
             print "Error $sql : $dbh->err \n" if $dbh->err;
-               }
-       }
+        }
+    }
 }
 
 #
@@ -1349,32 +1846,32 @@ foreach my $table ( keys %indexes ) {
 #
 print "Checking for foreign keys required...\n" unless $silent;
 foreach my $table ( keys %foreign_keys ) {
-       #
-       # read all indexes from $table
-       #
-       $sth = $dbh->prepare("show table status like '$table'");
-       $sth->execute;
-       my $stat = $sth->fetchrow_hashref;
-       # read indexes to check
-       my $tablerows = $foreign_keys{$table};
-       foreach my $row (@$tablerows) {
-               my $foreign_table=$row->{foreigntable};
-               if ($stat->{'Comment'} =~/$foreign_table/) {
-#                      print "$foreign_table existing\n";
-               } else {
-                       print "\tCreating foreign key $foreign_table in $table\n";
-                       # first, drop any orphan value in child table
-                       if ($row->{onDelete} ne "RESTRICT") {
-                               my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
-                               $dbh->do($sql);
-                               print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
-                       }
-                       my $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
-                       $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
-                       $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
-                       $dbh->do($sql);
-                       if ($dbh->err) {
-                               print "====================
+    #
+    # read all indexes from $table
+    #
+    $sth = $dbh->prepare("show table status like '$table'");
+    $sth->execute;
+    my $stat = $sth->fetchrow_hashref;
+    # read indexes to check
+    my $tablerows = $foreign_keys{$table};
+    foreach my $row (@$tablerows) {
+        my $foreign_table=$row->{foreigntable};
+        if ($stat->{'Comment'} =~/$foreign_table/) {
+#             print "$foreign_table existing\n";
+        } else {
+            print "\tCreating foreign key $foreign_table in $table\n";
+            # first, drop any orphan value in child table
+            if ($row->{onDelete} ne "RESTRICT") {
+                my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
+                $dbh->do($sql);
+                print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
+            }
+            my $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
+            $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
+            $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
+            $dbh->do($sql);
+            if ($dbh->err) {
+                print "====================
 An error occured during :
 \t$sql
 It probably means there is something wrong in your DB : a row ($table.$row->{key}) refers to a value in $row->{foreigntable}.$row->{foreignkey} that does not exist. solve the problem and run updater again (or just the previous SQL statement).
@@ -1382,9 +1879,19 @@ You can find those values with select
 \t$table.* from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})
 ====================\n
 ";
-                       }
-               }
-       }
+            }
+        }
+    }
+}
+# now drop useless tables
+foreach $table ( @TableToDelete ) {
+    if ( $existingtables{$table} ) {
+        print "Dropping unused table $table\n" if $debug and not $silent;
+        $dbh->do("drop table $table");
+        if ( $dbh->err ) {
+            print "Error : $dbh->errstr \n";
+        }
+    }
 }
 
 #
@@ -1404,271 +1911,348 @@ $sth->execute();
 my $definitions;
 my $bibliofwexist=0;
 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
-       $bibliofwexist=1 if $column eq 'frameworkcode';
+    $bibliofwexist=1 if $column eq 'frameworkcode';
 }
 unless ($bibliofwexist) {
-       print "moving biblioframework to biblio table\n";
-       $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
-       $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
-       $sth->execute;
-       my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
-       my $totaldone=0;
-       while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
-               $sth_update->execute($frameworkcode,$biblionumber);
-               $totaldone++;
-               print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
-       }
-       print "\rdone\n";
-}
-
-#
-# moving MARC data from marc_subfield_table to biblioitems.marc
-#
-$sth = $dbh->prepare("show columns from biblioitems");
-$sth->execute();
-my $definitions;
-my $marcdone=0;
-while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
-       $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
-}
-unless ($marcdone) {
-       print "moving MARC record to biblioitems table\n";
-       # changing marc field type
-       $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
-       # adding marc xml, just for convenience
-       $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ');
-       # moving data from marc_subfield_value to biblio
-       $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
-       $sth->execute;
-       my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
-       my $totaldone=0;
-       while (my ($bibid,$biblionumber) = $sth->fetchrow) {
-               my $record = MARCgetbiblio($dbh,$bibid);
-       #Force UTF-8 in record leader
-               $record->encoding('UTF-8');
-#              print $record->as_formatted if ($biblionumber==3902);
-               $sth_update->execute($record->as_usmarc(),$record->as_xml_record(),$biblionumber);
-               $totaldone++;
-               print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
-       }
-       print "\rdone\n";
+    print "moving biblioframework to biblio table\n";
+    $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
+    $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
+    $sth->execute;
+    my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
+    my $totaldone=0;
+    while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
+        $sth_update->execute($frameworkcode,$biblionumber);
+        $totaldone++;
+        print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
+    }
+    print "\rdone\n";
 }
 
-
 # at last, remove useless fields
 foreach $table ( keys %uselessfields ) {
-       my @fields = split /,/,$uselessfields{$table};
-       my $fields;
-       my $exists;
-       foreach my $fieldtodrop (@fields) {
-               $fieldtodrop =~ s/\t//g;
-               $fieldtodrop =~ s/\n//g;
-               $exists =0;
-               $sth = $dbh->prepare("show columns from $table");
-               $sth->execute;
-               while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
-               {
-                       $exists =1 if ($column eq $fieldtodrop);
-               }
-               if ($exists) {
-                       print "deleting $fieldtodrop field in $table...\n" unless $silent;
-                       my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
-                       $sth->execute;
-               }
-       }
-}    # foreach
-
-
-# MOVE all tables TO UTF-8 and innoDB
-$sth = $dbh->prepare("show table status");
-$sth->execute;
-while ( my $table = $sth->fetchrow_hashref ) {
-#      if ($table->{Engine} ne 'InnoDB') {
-#              $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
-#              print "moving $table->{Name} to InnoDB\n";
-#      }
-    next if $table->{Name} eq 'marc_word';
-    next if $table->{Name} eq 'marc_subfield_table';
-    next if $table->{Name} eq 'auth_word';
-    next if $table->{Name} eq 'auth_subfield_table';
-       unless ($table->{Collation} =~ /^utf8/) {
-               print "moving $table->{Name} to utf8\n";
-               $dbh->do("ALTER TABLE $table->{Name} CONVERT TO CHARACTER SET utf8");
-               $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
-               # FIXME : maybe a ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 would be better, def char set seems to work fine. If any problem encountered, let's try with convert !
-       } else {
-       }
-}
-
-$sth->finish;
-
-#
-# those 2 subs are a copy of Biblio.pm, version 2.2.4
-# they are useful only once, for moving from 2.2 to 3.0
-# the MARCgetbiblio & MARCgetitem subs in Biblio.pm
-# are still here, but uses other tables
-# (the ones that are filled by updatedatabase !)
-#
-
-sub MARCgetbiblio {
-
-    # Returns MARC::Record of the biblio passed in parameter.
-    my ( $dbh, $bibid ) = @_;
-    my $record = MARC::Record->new();
-#      warn "". $bidid;
-
-    my $sth =
-      $dbh->prepare(
-"select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
-                                from marc_subfield_table
-                                where bibid=? order by tag,tagorder,subfieldorder
-                        "
-    );
-    my $sth2 =
-      $dbh->prepare(
-        "select subfieldvalue from marc_blob_subfield where blobidlink=?");
-    $sth->execute($bibid);
-    my $prevtagorder = 1;
-    my $prevtag      = 'XXX';
-    my $previndicator;
-    my $field;        # for >=10 tags
-    my $prevvalue;    # for <10 tags
-    while ( my $row = $sth->fetchrow_hashref ) {
-
-        if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
-            $sth2->execute( $row->{'valuebloblink'} );
-            my $row2 = $sth2->fetchrow_hashref;
-            $sth2->finish;
-            $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
-        }
-        if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
-            $previndicator .= "  ";
-            if ( $prevtag < 10 ) {
-                               if ($prevtag ne '000') {
-                       $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
-                               } else {
-                                       $record->leader(sprintf("%24s",$prevvalue));
-                               }
-            }
-            else {
-                $record->add_fields($field) unless $prevtag eq "XXX";
-            }
-            undef $field;
-            $prevtagorder  = $row->{tagorder};
-            $prevtag       = $row->{tag};
-            $previndicator = $row->{tag_indicator};
-            if ( $row->{tag} < 10 ) {
-                $prevvalue = $row->{subfieldvalue};
-            }
-            else {
-                $field = MARC::Field->new(
-                    ( sprintf "%03s", $prevtag ),
-                    substr( $row->{tag_indicator} . '  ', 0, 1 ),
-                    substr( $row->{tag_indicator} . '  ', 1, 1 ),
-                    $row->{'subfieldcode'},
-                    $row->{'subfieldvalue'}
-                );
-            }
-        }
-        else {
-            if ( $row->{tag} < 10 ) {
-                $record->add_fields( ( sprintf "%03s", $row->{tag} ),
-                    $row->{'subfieldvalue'} );
-            }
-            else {
-                $field->add_subfields( $row->{'subfieldcode'},
-                    $row->{'subfieldvalue'} );
-            }
-            $prevtag       = $row->{tag};
-            $previndicator = $row->{tag_indicator};
-        }
-    }
-
-    # the last has not been included inside the loop... do it now !
-    if ( $prevtag ne "XXX" )
-    { # check that we have found something. Otherwise, prevtag is still XXX and we
-         # must return an empty record, not make MARC::Record fail because we try to
-         # create a record with XXX as field :-(
-        if ( $prevtag < 10 ) {
-            $record->add_fields( $prevtag, $prevvalue );
+    my @fields = split /,/,$uselessfields{$table};
+    my $fields;
+    my $exists;
+    foreach my $fieldtodrop (@fields) {
+        $fieldtodrop =~ s/\t//g;
+        $fieldtodrop =~ s/\n//g;
+        $exists =0;
+        $sth = $dbh->prepare("show columns from $table");
+        $sth->execute;
+        while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
+        {
+            $exists =1 if ($column eq $fieldtodrop);
         }
-        else {
-
-            #                  my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
-            $record->add_fields($field);
+        if ($exists) {
+            print "deleting $fieldtodrop field in $table...\n" unless $silent;
+            my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
+            $sth->execute;
         }
     }
-    return $record;
-}
-
-sub MARCgetitem {
-
-    # Returns MARC::Record of the biblio passed in parameter.
-    my ( $dbh, $bibid, $itemnumber ) = @_;
-    my $record = MARC::Record->new();
-
-    # search MARC tagorder
-    my $sth2 =
-      $dbh->prepare(
-"select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
-    );
-    $sth2->execute( $bibid, $itemnumber );
-    my ($tagorder) = $sth2->fetchrow_array();
-
-    #---- TODO : the leader is missing
-    my $sth =
-      $dbh->prepare(
-"select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
-                                from marc_subfield_table
-                                where bibid=? and tagorder=? order by subfieldcode,subfieldorder
-                        "
-    );
-    $sth2 =
-      $dbh->prepare(
-        "select subfieldvalue from marc_blob_subfield where blobidlink=?");
-    $sth->execute( $bibid, $tagorder );
-    while ( my $row = $sth->fetchrow_hashref ) {
-        if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
-            $sth2->execute( $row->{'valuebloblink'} );
-            my $row2 = $sth2->fetchrow_hashref;
-            $sth2->finish;
-            $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
-        }
-        if ( $record->field( $row->{'tag'} ) ) {
-            my $field;
-
-#--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
-            #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
-            if ( length( $row->{'tag'} ) < 3 ) {
-                $row->{'tag'} = "0" . $row->{'tag'};
-            }
-            $field = $record->field( $row->{'tag'} );
-            if ($field) {
-                my $x =
-                  $field->add_subfields( $row->{'subfieldcode'},
-                    $row->{'subfieldvalue'} );
-                $record->delete_field($field);
-                $record->add_fields($field);
-            }
-        }
-        else {
-            if ( length( $row->{'tag'} ) < 3 ) {
-                $row->{'tag'} = "0" . $row->{'tag'};
-            }
-            my $temp =
-              MARC::Field->new( $row->{'tag'}, " ", " ",
-                $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
-            $record->add_fields($temp);
-        }
+}    # foreach
 
-    }
-    return $record;
-}
+#
+# Changing aqbookfund's primary key 
+#
+$sth=$dbh->prepare("ALTER TABLE `aqbookfund` DROP PRIMARY KEY , ADD PRIMARY KEY ( `bookfundid` , `branchcode` ) ;");
+$sth->execute;
 
+$sth->finish;
 
 exit;
 
 # $Log$
+# Revision 1.158  2007/03/09 15:14:57  tipaul
+# rel_3_0 moved to HEAD
+#
+# Revision 1.157.2.56  2007/01/31 16:22:54  btoumi
+# -add possibility to use isbn with length of 13 characters
+# for  Import datas in the reservoir.
+# -modify isbn field in marc_breeding table (varchar 13)
+# -add isbn filter (no - )when u read a notice from reservoir
+# -add filter to have right field 100
+#
+# Revision 1.157.2.55  2007/01/30 10:50:19  tipaul
+# adding 2 usefull indexes to biblioitems table
+#
+# Revision 1.157.2.54  2007/01/29 16:45:52  toins
+# * adding a new default authorised value : SUGGEST.
+# SUGGEST give some reasons to accept or reject a suggestion.
+#
+# * default value for borrowersMandatoryfield syspref is now "cardnumber|surname|adress"
+#
+# Revision 1.157.2.53  2007/01/26 20:48:37  hdl
+# Serials management : Bugfixes + improvements.
+# - Partial dates are now managed
+# - next Date Calculation with irregularity tested for 1 week and 1 month.
+# - manage if subscription is abouttoexpire or expired.
+# - Adding some information on serials pages about subscription.
+# - Managing irregularity with numbers.
+# - Adding Internal Notes in subscription management.
+# - Repeating Button above pages.
+#
+# Please run Updatedatabase to change irregularity and add internalnotes field  to subscription
+#
+# Revision 1.157.2.52  2007/01/24 13:57:26  tipaul
+# - setting supplierid to auto_increment (HDL : could you check that is works, i'm not 100% sure)
+# - removing 22 -> 30 marc_subfield_table -> marcxml stuff, it's now in misc/migration_tools/22_to_30/
+#
+# Revision 1.157.2.51  2007/01/18 09:58:45  tipaul
+# defaulting NOT NULL fields (to '')
+#
+# Revision 1.157.2.50  2007/01/18 09:39:21  tipaul
+# issuedate must be defaulted with ' '
+#
+# Revision 1.157.2.49  2007/01/18 09:37:30  tipaul
+# removing 2 field definitions that were here twice
+#
+# Revision 1.157.2.48  2007/01/15 09:55:40  toins
+# adding a new logging systempref : FinesLog.
+#
+# Revision 1.157.2.47  2007/01/12 18:09:49  toins
+# LetterLog added
+#
+# Revision 1.157.2.46  2007/01/11 14:35:39  tipaul
+# adding Opac Browser feature : the build_browser_and_cloud.pl script will :
+# - fill the browser table, that enable browsing, digit by digit of a given category, the catalogue. A complete dewey classification is provided in the script, active only for french libraries, of course (although, for instance, the script check that the catalogue is in english for developping convenience)
+# - fill the tags table, that contains the subject cloud.
+#
+# The cloud part is a copy of the previous build_tags.pl script that can be deleted : those 2 scripts require to parse all the catalogue to extract interesting data, so they are long. It's useless to parse the catalogue twice !
+#
+# The commit also add the systempreference to hide/show the OpacBrowse in database & in systempref management script.
+#
+# IMPROVEMENTS to do :
+# - the script that builds the tables can be improved to update only last week biblios (at the price of a small error in value links, but it's not a problem).
+# - add, in parameters section, a place to edit browser descriptions. The build script has to be updated to to avoid deleting existing browser descriptions.
+#
+# Revision 1.157.2.45  2007/01/10 16:52:52  toins
+# Value for Log Features syspref are set to 0 by default.
+#
+# Revision 1.157.2.44  2007/01/10 16:31:15  toins
+# new systems preferences :
+#  - CataloguingLog (log the update/creation/deletion of a notice if set to 1)
+#  - BorrowersLog ( idem for borrowers )
+#  - IssueLog (log all issue if set to 1)
+#  - ReturnLog (log all return if set to 1)
+#  - SusbcriptionLog (log all creation/deletion/update of a subcription)
+#
+# All of theses are in a new tab called 'LOGFeatures' in systempreferences.pl
+#
+# Revision 1.157.2.43  2007/01/10 14:13:17  toins
+# opac_news.displayed is replaced by opac_news.number.
+# This field say how are ordered the news on the template.
+#
+# Revision 1.157.2.42  2007/01/09 14:09:01  toins
+# 2 field added to opac_news.('expirationdate' and 'displayed').
+#
+# Revision 1.157.2.41  2006/12/22 17:11:33  tipaul
+# adding 3 systempreferences for opac features & a new systempref tab where all systempreferences are located
+#
+# Revision 1.157.2.40  2006/12/20 16:45:59  tipaul
+# ZEBRA update :
+# - adding a new table : when a biblio is added/modified/ deleted, an entry is entered in this table
+# - the zebraqueue_start.pl script read it & does the stuff.
+#
+# code coming from head (tumer). it can be run every minut instead of once every day for dev_week code.
+#
+# I just have commented the previous code (=real time update) in Biblio.pm, we will be able to reactivate it once indexdata fixes zebra update bug !
+#
+# Revision 1.157.2.39  2006/12/20 11:42:17  toins
+# adding table "tags"
+#
+# Revision 1.157.2.38  2006/12/19 12:06:53  alaurin
+# adding a new system preference : RequestOnOpac ;
+#
+# adding update database
+#
+# Revision 1.157.2.37  2006/12/19 10:49:21  toins
+# fix a minor bug in syspref "expandedSearchOption" and adding it on updatedatabase.
+#
+# Revision 1.157.2.36  2006/12/13 19:48:09  hdl
+# Adding claimdate to serials.
+# (Needed to record claimdate
+#
+# Revision 1.157.2.35  2006/12/08 15:36:57  hdl
+# Adding issuedate to issues table.
+#
+# Revision 1.157.2.34  2006/12/07 16:00:41  hdl
+# Adding issuedate to table issues.
+# Modifying issuedate on issue (Circ2.pm)
+# Modifying report issue_avg_stats to take this change into account. (Need TESTING)
+#
+# Revision 1.157.2.33  2006/12/06 14:12:18  btoumi
+# add BorrowersTitles systempreferences to setup borrowers title
+#
+# Revision 1.157.2.32  2006/12/06 13:49:41  toins
+# deleting additionalauthors, bibliosubjects, bibliosubtitles.
+#
+# Revision 1.157.2.31  2006/12/05 15:07:16  tipaul
+# NEW FEATURE :
+# a column (itemtypes.summary) has been added.
+#
+# If it is empty, no changes at all.
+# In admin/itemtypes.pl, the librarian can go and define what (and how) the record appeard below the title.
+# The summary must be entered exactly as the authority summary.
+# An example is provided in admin/itemtypes.pl add/modify itemtype.
+#
+# This feature had been requested for a while by my librarians. The 2 uses we can imagine are :
+# - for websites => show the link directly in the result list, to avoid 1 clic (& there is no need for a size/editor/publicationyear for web sites)
+# - for serial publications => show some serial specific informations.
+#
+# This commit should do everything that is needed for this feature.
+#
+# Revision 1.157.2.30  2006/11/29 11:58:18  toins
+# re indenting with space.
+#
+# Revision 1.157.2.29  2006/11/24 21:58:35  kados
+# changing items.itemtype to items.itype to avoid problems with
+# joins with biblioitems. NOTE: I don't think updatedatabase will remove the
+# items.itemtype from your db so you must do that manually if you updated
+# from an earlier version of updatedatabase.
+#
+# Revision 1.157.2.28  2006/11/24 13:54:55  hdl
+# Adding serialsadditem
+#
+# Revision 1.157.2.27  2006/11/24 11:07:09  alaurin
+# bug sanop #74 :
+#
+# Add a new system prefence "AutoLocation"
+#  this fonction  switching activation or not Autolocation, if Yes, the Librarian can't change his location, it's defined by branchip,
+# if autolocation is setting to "NO", librarian can change his settings ....
+#
+#
+# warn, if autolocation is setting "on", on circulation.pl we don't have anymore the choice to change your library and branchprinter,
+# defined on branches : branchip and branchprinter ....
+#
+# this function could be improved
+#
+# Revision 1.157.2.26  2006/11/23 11:01:06  toins
+# branchtransfers.frombranch & branchtransfers.tobranch must be VARCHAR(10)
+#
+# Revision 1.157.2.25  2006/11/23 09:05:33  tipaul
+# reintroducing move to innoDB (as only innoDB supports extended features like foreign keys)
+#
+# Revision 1.157.2.24  2006/11/21 09:15:23  toins
+# better userflag description
+#
+# Revision 1.157.2.23  2006/11/21 08:51:01  toins
+# 2 new userflags: serials & reports.
+#
+# Revision 1.157.2.22  2006/11/20 16:59:09  toins
+# adding a userflags: 'editauthorities'.
+#
+# Revision 1.157.2.21  2006/11/17 10:53:04  hdl
+# Changing
+# - subscription detail :
+#     adding manual history (in subscription table)
+#     addind subscription summary.
+# - menu-serials.inc deleting old link
+# - adapting serials-collection.pl
+#
+# TODO List :
+# - Some values are hard coded in subscription-detail
+# - subscription-detail.pl relies on subscription-add for edition BUT subscription-add transmits back data to subscription-detail in order to save data back into database. This is a bit odd enough and should not occur.
+# - Some more tests on numberlength which doesnot seem to be kept.
+#
+# Revision 1.157.2.20  2006/11/15 15:15:50  hdl
+# Final First Version for New Facility for subscription management.
+#
+# Now
+# use serials-collection.pl for history display
+# and serials-edit.pl for serial edition
+# subscription add and detail adds a new branch information to help IndependantBranches Library to manage different subscriptions for a serial
+#
+# This is aimed at replacing serials-receive and statecollection.
+#
+# Revision 1.157.2.19  2006/11/14 16:28:01  rych
+# Adding itemtype field to items
+#
+# Revision 1.157.2.18  2006/11/14 16:16:58  rych
+# fix mysql syntax
+#
+# Revision 1.157.2.17  2006/11/14 14:39:31  toins
+# * delete the userflags "reservforself" which is unused.
+# * some new function not use at the moment.
+#
+# Revision 1.157.2.16  2006/11/02 09:27:30  toins
+# issue.branchcode must be varchar(10).
+#
+# Revision 1.157.2.15  2006/10/31 17:41:51  toins
+# items.holdingbranch must be varchar(10)
+#
+# Revision 1.157.2.14  2006/10/30 09:41:45  btoumi
+# remove auto increment for accountno in accountlines table
+#
+# Revision 1.157.2.13  2006/10/20 10:35:05  alaurin
+# new program : branchoverdues.pl
+#
+# with this program, the librararians will can check , and specify the method of notification of documents in overdue
+#
+# little explanation :
+#
+#     - At first, the datas come from accountlines, generated by accounlines (type 'FU')
+#     - There is three levels of notification (come from overduerules ....)
+#     - there is four methods of notification :
+#         - letter (for us, use an openoffice program ....)
+#         - Mail (use a batch program)
+#         - Phone (simple Method, if this method is selected, we consider that the borrower as been notified)
+#         - Considered Lost (For us the third level)
+#
+#     - At this time we have some parameters hardcoded (Must be improve later)
+#
+#     - the choice of methods is hardcoded :
+#         - for the first overduelevel : three methods : mail,letter,phone
+#         -For the second overduelevel :only one method : letter
+#         - For the Third Overdue level : only one method : Considered Lost
+#
+#
+# this program will be heavy tested next week ....
+#
+# Revision 1.157.2.12  2006/10/19 09:04:07  toins
+# itemtypes.itemtype is a primary key.
+#
+# Revision 1.157.2.11  2006/10/18 13:31:13  toins
+# Borrowers.categorycode must have 10 chars lenght & categories.categorycode must be a primary key.
+#
+# Revision 1.157.2.10  2006/10/17 16:18:14  hdl
+# Changing primary key in aqbookfund.
+# Making it branchcode+aqbookfundid rather than simple aqbookfundid.
+#
+# Revision 1.157.2.9  2006/10/16 14:23:47  toins
+# Borrowers.branchcode must be varchar(10) too.
+#
+# Revision 1.157.2.7  2006/10/11 15:22:23  tipaul
+# - adding some missing fields, coming from dev_week :
+# * lcsort & ccode in biblioitems table. lcsort is used for loc callnumbers & ccode is used to have a item level circulation rules. Ccode means C<irc>code
+# * onloan & issue_date in items table. They are filled by the misc/update_items.pl script, with circulation values. NOW, onloan & issue_date in items are NOT set by circulation, this decision speed up a lot the circulation rate (with the Date::Manip removal). The price for this is to have the status of the item not real time updated in zebra, but that's worth the price.
+# * cutterextra in items, that we should ask tumer to understand what it does  ;-)
+#
+# Revision 1.157.2.6  2006/10/10 11:25:40  btoumi
+# add two tables : notifys , charges
+# modify accountlines tables add two fields (notify_id and notify_level)
+#
+# Revision 1.157.2.5  2006/10/02 09:15:44  hdl
+# Serials :
+# * synching with NZ-devs on Serials.
+# * adding routing lists support,
+# * adding serialsadditems support
+# * adding publisheddate management
+#
+# TODO :
+# Management for seasonal serials should be fixed in order to be language independant.
+#
+# Revision 1.157.2.4  2006/09/19 07:44:13  btoumi
+# bug fix : modify wrong field name BorrowerMandatoryField
+#
+# Revision 1.157.2.3  2006/09/18 14:00:24  btoumi
+# bug fix :wrond field name for opacnote and contactnote
+#
+# Revision 1.157.2.2  2006/09/11 13:24:03  alaurin
+# marcxml should be a longtext, some biblios can be more than 65535 char long
+#
+# Revision 1.157.2.1  2006/09/04 08:39:14  toins
+# sync with rel_2_2.
+#
 # Revision 1.157  2006/08/11 10:03:13  tipaul
 # the new "includes" features, for personalized templates. Look at koha-devel, i'll write a mail here (& something on the wiki)
 #
@@ -1791,7 +2375,7 @@ exit;
 # Revision 1.130  2006/03/03 16:35:21  tipaul
 # commit for holidays and news management.
 #
-# Contrib from Tümer Garip (from Turkey) :
+# Contrib from Tmer Garip (from Turkey) :
 # * holiday :
 # in /tools/ the holiday.pl script let you define holidays (days where the library is closed), branch by branch. You can define 3 types of holidays :
 # - single day : only this day is closed