Bug 22521: DBRev 18.12.00.055
[koha.git] / Koha / Plugins / Base.pm
1 package Koha::Plugins::Base;
2
3 # Copyright 2012 Kyle Hall
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use Module::Pluggable require => 1;
23 use Cwd qw(abs_path);
24 use List::Util qw(max);
25
26 use base qw{Module::Bundled::Files};
27
28 use C4::Context;
29 use C4::Output qw(output_with_http_headers output_html_with_http_headers);
30
31 =head1 NAME
32
33 Koha::Plugins::Base - Base Module for plugins
34
35 =cut
36
37 sub new {
38     my ( $class, $args ) = @_;
39
40     return unless ( C4::Context->config("enable_plugins") || $args->{'enable_plugins'} );
41
42     $args->{'class'} = $class;
43     $args->{'template'} = Template->new( { ABSOLUTE => 1, ENCODING => 'UTF-8' } );
44
45     my $self = bless( $args, $class );
46
47     my $plugin_version = $self->get_metadata->{version};
48     my $database_version = $self->retrieve_data('__INSTALLED_VERSION__') || 0;
49
50     ## Run the installation method if it exists and hasn't been run before
51     if ( $self->can('install') && !$self->retrieve_data('__INSTALLED__') ) {
52         if ( $self->install() ) {
53             $self->store_data( { '__INSTALLED__' => 1 } );
54             if ( my $version = $plugin_version ) {
55                 $self->store_data({ '__INSTALLED_VERSION__' => $version });
56             }
57         } else {
58             warn "Plugin $class failed during installation!";
59         }
60     } elsif ( $self->can('upgrade') ) {
61         if ( _version_compare( $plugin_version, $database_version ) == 1 ) {
62             if ( $self->upgrade() ) {
63                 $self->store_data({ '__INSTALLED_VERSION__' => $plugin_version });
64             } else {
65                 warn "Plugin $class failed during upgrade!";
66             }
67         }
68     } elsif ( $plugin_version ne $database_version ) {
69         $self->store_data({ '__INSTALLED_VERSION__' => $plugin_version });
70     }
71
72     return $self;
73 }
74
75 =head2 store_data
76
77 store_data allows a plugin to store key value pairs in the database for future use.
78
79 usage: $self->store_data({ param1 => 'param1val', param2 => 'param2value' })
80
81 =cut
82
83 sub store_data {
84     my ( $self, $data ) = @_;
85
86     my $dbh = C4::Context->dbh;
87     my $sql = "REPLACE INTO plugin_data SET plugin_class = ?, plugin_key = ?, plugin_value = ?";
88     my $sth = $dbh->prepare($sql);
89
90     foreach my $key ( keys %$data ) {
91         $sth->execute( $self->{'class'}, $key, $data->{$key} );
92     }
93 }
94
95 =head2 retrieve_data
96
97 retrieve_data allows a plugin to read the values that were previously saved with store_data
98
99 usage: my $value = $self->retrieve_data( $key );
100
101 =cut
102
103 sub retrieve_data {
104     my ( $self, $key ) = @_;
105
106     my $dbh = C4::Context->dbh;
107     my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
108     my $sth = $dbh->prepare($sql);
109     $sth->execute( $self->{'class'}, $key );
110     my $row = $sth->fetchrow_hashref();
111
112     return $row->{'plugin_value'};
113 }
114
115 =head2 get_template
116
117 get_template returns a Template object. Eventually this will probably be calling
118 C4:Template, but at the moment, it does not.
119
120 =cut
121
122 sub get_template {
123     my ( $self, $args ) = @_;
124
125     require C4::Auth;
126
127     my $template_name = $args->{'file'} // '';
128     # if not absolute, call mbf_path, which dies if file does not exist
129     $template_name = $self->mbf_path( $template_name )
130         if $template_name !~ m/^\//;
131     my ( $template, $loggedinuser, $cookie ) = C4::Auth::get_template_and_user(
132         {   template_name   => $template_name,
133             query           => $self->{'cgi'},
134             type            => "intranet",
135             authnotrequired => 1,
136         }
137     );
138
139     $template->param(
140         CLASS       => $self->{'class'},
141         METHOD      => scalar $self->{'cgi'}->param('method'),
142         PLUGIN_PATH => $self->get_plugin_http_path(),
143     );
144
145     return $template;
146 }
147
148 sub get_metadata {
149     my ( $self, $args ) = @_;
150
151     return $self->{'metadata'};
152 }
153
154 =head2 get_qualified_table_name
155
156 To avoid naming conflict, each plugins tables should use a fully qualified namespace.
157 To avoid hardcoding and make plugins more flexible, this method will return the proper
158 fully qualified table name.
159
160 usage: my $table = $self->get_qualified_table_name( 'myTable' );
161
162 =cut
163
164 sub get_qualified_table_name {
165     my ( $self, $table_name ) = @_;
166
167     return lc( join( '_', split( '::', $self->{'class'} ), $table_name ) );
168 }
169
170 =head2 get_plugin_http_path
171
172 To access a plugin's own resources ( images, js files, css files, etc... )
173 a plugin will need to know what path to use in the template files. This
174 method returns that path.
175
176 usage: my $path = $self->get_plugin_http_path();
177
178 =cut
179
180 sub get_plugin_http_path {
181     my ($self) = @_;
182
183     return "/plugin/" . join( '/', split( '::', $self->{'class'} ) );
184 }
185
186 =head2 go_home
187
188    go_home is a quick redirect to the Koha plugins home page
189
190 =cut
191
192 sub go_home {
193     my ( $self, $params ) = @_;
194
195     print $self->{'cgi'}->redirect("/cgi-bin/koha/plugins/plugins-home.pl");
196 }
197
198 =head2 output_html
199
200     $self->output_html( $data, $status, $extra_options );
201
202 Outputs $data setting the right headers for HTML content.
203
204 Note: this is a wrapper function for C4::Output::output_with_http_headers
205
206 =cut
207
208 sub output_html {
209     my ( $self, $data, $status, $extra_options ) = @_;
210     output_with_http_headers( $self->{cgi}, undef, $data, 'html', $status, $extra_options );
211 }
212
213 =head2 output
214
215    $self->output( $data, $content_type[, $status[, $extra_options]]);
216
217 Outputs $data with the appropriate HTTP headers,
218 the authentication cookie and a Content-Type specified in
219 $content_type.
220
221 $content_type is one of the following: 'html', 'js', 'json', 'xml', 'rss', or 'atom'.
222
223 $status is an HTTP status message, like '403 Authentication Required'. It defaults to '200 OK'.
224
225 $extra_options is hashref.  If the key 'force_no_caching' is present and has
226 a true value, the HTTP headers include directives to force there to be no
227 caching whatsoever.
228
229 Note: this is a wrapper function for C4::Output::output_with_http_headers
230
231 =cut
232
233 sub output {
234     my ( $self, $data, $content_type, $status, $extra_options ) = @_;
235     output_with_http_headers( $self->{cgi}, undef, $data, $content_type, $status, $extra_options );
236 }
237
238 =head2 _version_compare
239
240 Utility method to compare two version numbers.
241 Returns 1 if the first argument is the higher version
242 Returns -1 if the first argument is the lower version
243 Returns 0 if both versions are equal
244
245 if ( _version_compare( '2.6.26', '2.6.0' ) == 1 ) {
246     print "2.6.26 is greater than 2.6.0\n";
247 }
248
249 =cut
250
251 sub _version_compare {
252     my $ver1 = shift || 0;
253     my $ver2 = shift || 0;
254
255     my @v1 = split /[.+:~-]/, $ver1;
256     my @v2 = split /[.+:~-]/, $ver2;
257
258     for ( my $i = 0 ; $i < max( scalar(@v1), scalar(@v2) ) ; $i++ ) {
259
260         # Add missing version parts if one string is shorter than the other
261         # i.e. 0 should be lt 0.2.1 and not equal, so we append .0
262         # 0.0.0 <=> 0.2.1 = -1
263         push( @v1, 0 ) unless defined( $v1[$i] );
264         push( @v2, 0 ) unless defined( $v2[$i] );
265         if ( int( $v1[$i] ) > int( $v2[$i] ) ) {
266             return 1;
267         }
268         elsif ( int( $v1[$i] ) < int( $v2[$i] ) ) {
269             return -1;
270         }
271     }
272     return 0;
273 }
274
275 1;
276 __END__
277
278 =head1 AUTHOR
279
280 Kyle M Hall <kyle.m.hall@gmail.com>
281
282 =cut