Bug 29121: Catch errors in ->install and ->upgrade calls on plugins
[koha-ffzg.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 Cwd qw( abs_path );
23 use List::Util qw( max );
24 use Try::Tiny;
25
26 use base qw{Module::Bundled::Files};
27
28 use C4::Context;
29 use C4::Output qw( output_with_http_headers );
30
31 use Koha::Exceptions::Plugin;
32
33 =head1 NAME
34
35 Koha::Plugins::Base - Base Module for plugins
36
37 =cut
38
39 sub new {
40     my ( $class, $args ) = @_;
41
42     return unless ( C4::Context->config("enable_plugins") || $args->{'enable_plugins'} );
43
44     $args->{'class'} = $class;
45     $args->{'template'} = Template->new( { ABSOLUTE => 1, ENCODING => 'UTF-8' } );
46
47     my $self = bless( $args, $class );
48
49     my $plugin_version = $self->get_metadata->{version};
50     my $database_version = $self->retrieve_data('__INSTALLED_VERSION__') || 0;
51
52     ## Run the installation method if it exists and hasn't been run before
53     if ( $self->can('install') && !$self->retrieve_data('__INSTALLED__') ) {
54         try {
55             if ( $self->install() ) {
56                 $self->store_data( { '__INSTALLED__' => 1, '__ENABLED__' => 1 } );
57                 if ( my $version = $plugin_version ) {
58                     $self->store_data({ '__INSTALLED_VERSION__' => $version });
59                 }
60             } else {
61                 warn "Plugin $class failed during installation!";
62             }
63         }
64         catch {
65             Koha::Exceptions::Plugin::InstallDied->throw( plugin_class => $class );
66         };
67     } elsif ( $self->can('upgrade') ) {
68         if ( _version_compare( $plugin_version, $database_version ) == 1 ) {
69             try {
70                 if ( $self->upgrade() ) {
71                     $self->store_data({ '__INSTALLED_VERSION__' => $plugin_version });
72                 } else {
73                     warn "Plugin $class failed during upgrade!";
74                 }
75             }
76             catch {
77                 Koha::Exceptions::Plugin::UpgradeDied->throw( plugin_class => $class );
78             };
79         }
80     } elsif ( $plugin_version ne $database_version ) {
81         $self->store_data({ '__INSTALLED_VERSION__' => $plugin_version });
82     }
83
84     $self->{_bundle_path} = abs_path($self->mbf_dir);
85
86     return $self;
87 }
88
89 =head2 store_data
90
91 store_data allows a plugin to store key value pairs in the database for future use.
92
93 usage: $self->store_data({ param1 => 'param1val', param2 => 'param2value' })
94
95 =cut
96
97 sub store_data {
98     my ( $self, $data ) = @_;
99
100     my $dbh = C4::Context->dbh;
101     my $sql = "REPLACE INTO plugin_data SET plugin_class = ?, plugin_key = ?, plugin_value = ?";
102     my $sth = $dbh->prepare($sql);
103
104     foreach my $key ( keys %$data ) {
105         $sth->execute( $self->{'class'}, $key, $data->{$key} );
106     }
107 }
108
109 =head2 retrieve_data
110
111 retrieve_data allows a plugin to read the values that were previously saved with store_data
112
113 usage: my $value = $self->retrieve_data( $key );
114
115 =cut
116
117 sub retrieve_data {
118     my ( $self, $key ) = @_;
119
120     my $dbh = C4::Context->dbh;
121     my $sql = "SELECT plugin_value FROM plugin_data WHERE plugin_class = ? AND plugin_key = ?";
122     my $sth = $dbh->prepare($sql);
123     $sth->execute( $self->{'class'}, $key );
124     my $row = $sth->fetchrow_hashref();
125
126     return $row->{'plugin_value'};
127 }
128
129 =head2 get_template
130
131 get_template returns a Template object. Eventually this will probably be calling
132 C4:Template, but at the moment, it does not.
133
134 The returned template contains 3 variables that can be used in the plugin
135 templates:
136
137 =over 8
138
139 =item B<CLASS>
140
141 The name of the plugin class.
142
143 =item B<METHOD>
144
145 Then name of the plugin method used. For example 'tool' or 'report'.
146
147 =item B<PLUGIN_PATH>
148
149 The URL path to the plugin. It can be used in templates in order to localize
150 ressources like images in html tags, or other templates.
151
152 =item B<PLUGIN_DIR>
153
154 The absolute pathname to the plugin directory. Necessary to include other
155 templates from a template with the [% INCLUDE %] directive.
156
157 =back
158
159
160 =cut
161
162 sub get_template {
163     my ( $self, $args ) = @_;
164
165     require C4::Auth;
166
167     my $template_name = $args->{'file'} // '';
168     # if not absolute, call mbf_path, which dies if file does not exist
169     $template_name = $self->mbf_path( $template_name )
170         if $template_name !~ m/^\//;
171     my ( $template, $loggedinuser, $cookie ) = C4::Auth::get_template_and_user(
172         {   template_name   => $template_name,
173             query           => $self->{'cgi'},
174             type            => "intranet",
175             authnotrequired => 1,
176         }
177     );
178     $template->param(
179         CLASS       => $self->{'class'},
180         METHOD      => scalar $self->{'cgi'}->param('method'),
181         PLUGIN_PATH => $self->get_plugin_http_path(),
182         PLUGIN_DIR  => $self->bundle_path(),
183         LANG        => C4::Languages::getlanguage($self->{'cgi'}),
184     );
185
186     return $template;
187 }
188
189 sub get_metadata {
190     my ( $self, $args ) = @_;
191
192     #FIXME: Why another encoding issue? For metadata containing non latin characters.
193     my $metadata = $self->{metadata};
194     defined($metadata->{$_}) && utf8::decode($metadata->{$_}) for keys %$metadata;
195     return $metadata;
196 }
197
198 =head2 get_qualified_table_name
199
200 To avoid naming conflict, each plugins tables should use a fully qualified namespace.
201 To avoid hardcoding and make plugins more flexible, this method will return the proper
202 fully qualified table name.
203
204 usage: my $table = $self->get_qualified_table_name( 'myTable' );
205
206 =cut
207
208 sub get_qualified_table_name {
209     my ( $self, $table_name ) = @_;
210
211     return lc( join( '_', split( '::', $self->{'class'} ), $table_name ) );
212 }
213
214 =head2 get_plugin_http_path
215
216 To access a plugin's own resources ( images, js files, css files, etc... )
217 a plugin will need to know what path to use in the template files. This
218 method returns that path.
219
220 usage: my $path = $self->get_plugin_http_path();
221
222 =cut
223
224 sub get_plugin_http_path {
225     my ($self) = @_;
226
227     return "/plugin/" . join( '/', split( '::', $self->{'class'} ) );
228 }
229
230 =head2 go_home
231
232    go_home is a quick redirect to the Koha plugins home page
233
234 =cut
235
236 sub go_home {
237     my ( $self, $params ) = @_;
238
239     print $self->{'cgi'}->redirect("/cgi-bin/koha/plugins/plugins-home.pl");
240 }
241
242 =head2 output_html
243
244     $self->output_html( $data, $status, $extra_options );
245
246 Outputs $data setting the right headers for HTML content.
247
248 Note: this is a wrapper function for C4::Output::output_with_http_headers
249
250 =cut
251
252 sub output_html {
253     my ( $self, $data, $status, $extra_options ) = @_;
254     output_with_http_headers( $self->{cgi}, undef, $data, 'html', $status, $extra_options );
255 }
256
257 =head2 bundle_path
258
259     my $bundle_path = $self->bundle_path
260
261 Returns the directory in which bundled files are.
262
263 =cut
264
265 sub bundle_path {
266     my ($self) = @_;
267
268     return $self->{_bundle_path};
269 }
270
271 =head2 output
272
273    $self->output( $data, $content_type[, $status[, $extra_options]]);
274
275 Outputs $data with the appropriate HTTP headers,
276 the authentication cookie and a Content-Type specified in
277 $content_type.
278
279 $content_type is one of the following: 'html', 'js', 'json', 'xml', 'rss', or 'atom'.
280
281 $status is an HTTP status message, like '403 Authentication Required'. It defaults to '200 OK'.
282
283 $extra_options is hashref.  If the key 'force_no_caching' is present and has
284 a true value, the HTTP headers include directives to force there to be no
285 caching whatsoever.
286
287 Note: this is a wrapper function for C4::Output::output_with_http_headers
288
289 =cut
290
291 sub output {
292     my ( $self, $data, $content_type, $status, $extra_options ) = @_;
293     output_with_http_headers( $self->{cgi}, undef, $data, $content_type, $status, $extra_options );
294 }
295
296 =head2 _version_compare
297
298 Utility method to compare two version numbers.
299 Returns 1 if the first argument is the higher version
300 Returns -1 if the first argument is the lower version
301 Returns 0 if both versions are equal
302
303 if ( _version_compare( '2.6.26', '2.6.0' ) == 1 ) {
304     print "2.6.26 is greater than 2.6.0\n";
305 }
306
307 =cut
308
309 sub _version_compare {
310     my @args = @_;
311
312     if ( $args[0]->isa('Koha::Plugins::Base') ) {
313         shift @args;
314     }
315
316     my $ver1 = shift @args || 0;
317     my $ver2 = shift @args || 0;
318
319     my @v1 = split /[.+:~-]/, $ver1;
320     my @v2 = split /[.+:~-]/, $ver2;
321
322     for ( my $i = 0 ; $i < max( scalar(@v1), scalar(@v2) ) ; $i++ ) {
323
324         # Add missing version parts if one string is shorter than the other
325         # i.e. 0 should be lt 0.2.1 and not equal, so we append .0
326         # 0.0.0 <=> 0.2.1 = -1
327         push( @v1, 0 ) unless defined( $v1[$i] );
328         push( @v2, 0 ) unless defined( $v2[$i] );
329         if ( int( $v1[$i] ) > int( $v2[$i] ) ) {
330             return 1;
331         }
332         elsif ( int( $v1[$i] ) < int( $v2[$i] ) ) {
333             return -1;
334         }
335     }
336     return 0;
337 }
338
339 =head2 is_enabled
340
341 Method that returns wether the plugin is enabled or not
342
343 $plugin->enable
344
345 =cut
346
347 sub is_enabled {
348     my ($self) = @_;
349
350     return $self->retrieve_data( '__ENABLED__' );
351 }
352
353 =head2 enable
354
355 Method for enabling plugin
356
357 $plugin->enable
358
359 =cut
360
361 sub enable {
362     my ($self) = @_;
363
364     $self->store_data( {'__ENABLED__' => 1}  );
365
366     return $self;
367 }
368
369 =head2 disable
370
371 Method for disabling plugin
372
373 $plugin->disable
374
375 =cut
376
377 sub disable {
378     my ($self) = @_;
379
380     $self->store_data( {'__ENABLED__' => 0}  );
381
382     return $self;
383 }
384
385 1;
386 __END__
387
388 =head1 AUTHOR
389
390 Kyle M Hall <kyle.m.hall@gmail.com>
391
392 =cut