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