Bug 30287: (follow-up) Add content wrap matching send time
[koha.git] / Koha / Plugins.pm
1 package Koha::Plugins;
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 Array::Utils qw( array_minus );
23 use Class::Inspector;
24 use List::MoreUtils qw( any );
25 use Module::Load::Conditional qw( can_load );
26 use Module::Load;
27 use Module::Pluggable search_path => ['Koha::Plugin'], except => qr/::Edifact(|::Line|::Message|::Order|::Segment|::Transport)$/;
28 use Try::Tiny;
29
30 use C4::Context;
31 use C4::Output;
32
33 use Koha::Cache::Memory::Lite;
34 use Koha::Exceptions::Plugin;
35 use Koha::Plugins::Methods;
36
37 use constant ENABLED_PLUGINS_CACHE_KEY => 'enabled_plugins';
38
39 BEGIN {
40     my $pluginsdir = C4::Context->config("pluginsdir");
41     my @pluginsdir = ref($pluginsdir) eq 'ARRAY' ? @$pluginsdir : $pluginsdir;
42     push @INC, array_minus(@pluginsdir, @INC) ;
43     pop @INC if $INC[-1] eq '.';
44 }
45
46 =head1 NAME
47
48 Koha::Plugins - Module for loading and managing plugins.
49
50 =head2 new
51
52 Constructor
53
54 =cut
55
56 sub new {
57     my ( $class, $args ) = @_;
58
59     return unless ( C4::Context->config("enable_plugins") || $args->{'enable_plugins'} );
60
61     $args->{'pluginsdir'} = C4::Context->config("pluginsdir");
62
63     return bless( $args, $class );
64 }
65
66 =head2 call
67
68 Calls a plugin method for all enabled plugins
69
70     @responses = Koha::Plugins->call($method, @args)
71
72 Note: Pass your arguments as refs, when you want subsequent plugins to use the value
73 updated by preceding plugins, provided that these plugins support that.
74
75 =cut
76
77 sub call {
78     my ($class, $method, @args) = @_;
79
80     return unless C4::Context->config('enable_plugins');
81
82     my @responses;
83     my @plugins = $class->get_enabled_plugins();
84     @plugins = grep { $_->can($method) } @plugins;
85
86     # TODO: Remove warn when after_hold_create is removed from the codebase
87     warn "after_hold_create is deprecated and will be removed soon. Contact the following plugin's authors: " . join( ', ', map {$_->{metadata}->{name}} @plugins)
88         if $method eq 'after_hold_create' and @plugins;
89
90     foreach my $plugin (@plugins) {
91         my $response = eval { $plugin->$method(@args) };
92         if ($@) {
93             warn sprintf("Plugin error (%s): %s", $plugin->get_metadata->{name}, $@);
94             next;
95         }
96
97         push @responses, $response;
98     }
99
100     return @responses;
101 }
102
103 =head2 get_enabled_plugins
104
105 Returns a list of enabled plugins.
106
107     @plugins = Koha::Plugins->get_enabled_plugins( [ verbose => 1 ] );
108
109 =cut
110
111 sub get_enabled_plugins {
112     my ( $class, $params ) = @_;
113
114     return unless C4::Context->config('enable_plugins');
115
116     my $enabled_plugins = Koha::Cache::Memory::Lite->get_from_cache(ENABLED_PLUGINS_CACHE_KEY);
117     unless ($enabled_plugins) {
118         my $verbose = $params->{verbose} // $class->_verbose;
119         $enabled_plugins = [];
120         my $rs = Koha::Database->schema->resultset('PluginData');
121         $rs = $rs->search({ plugin_key => '__ENABLED__', plugin_value => 1 });
122         my @plugin_classes = $rs->get_column('plugin_class')->all();
123         foreach my $plugin_class (@plugin_classes) {
124             next unless can_load( modules => { $plugin_class => undef }, verbose => $verbose, nocache => 1 );
125
126             my $plugin = eval { $plugin_class->new() };
127             if ($@ || !$plugin) {
128                 warn "Failed to instantiate plugin $plugin_class: $@";
129                 next;
130             }
131
132             push @$enabled_plugins, $plugin;
133         }
134         Koha::Cache::Memory::Lite->set_in_cache(ENABLED_PLUGINS_CACHE_KEY, $enabled_plugins);
135     }
136
137     return @$enabled_plugins;
138 }
139
140 sub _verbose {
141     my $class = shift;
142     # Return false when running unit tests
143     return exists $ENV{_} && $ENV{_} =~ /\/prove(\s|$)|\.t$/ ? 0 : 1;
144 }
145
146 =head2 feature_enabled
147
148 Returns a boolean denoting whether a plugin based feature is enabled or not.
149
150     $enabled = Koha::Plugins->feature_enabled('method_name');
151
152 =cut
153
154 sub feature_enabled {
155     my ( $class, $method ) = @_;
156
157     return 0 unless C4::Context->config('enable_plugins');
158
159     my $key     = "ENABLED_PLUGIN_FEATURE_" . $method;
160     my $feature = Koha::Cache::Memory::Lite->get_from_cache($key);
161     unless ( defined($feature) ) {
162         my @plugins = $class->get_enabled_plugins();
163         my $enabled = any { $_->can($method) } @plugins;
164         Koha::Cache::Memory::Lite->set_in_cache( $key, $enabled );
165     }
166     return $feature;
167 }
168
169 =head2 GetPlugins
170
171 This will return a list of all available plugins, optionally limited by
172 method or metadata value.
173
174     my @plugins = Koha::Plugins::GetPlugins({
175         method => 'some_method',
176         metadata => { some_key => 'some_value' },
177         [ verbose => 1 ],
178     });
179
180 The method and metadata parameters are optional.
181 If you pass multiple keys in the metadata hash, all keys must match.
182
183 =cut
184
185 sub GetPlugins {
186     my ( $self, $params ) = @_;
187
188     my $method       = $params->{method};
189     my $req_metadata = $params->{metadata} // {};
190     my $verbose      = delete $params->{verbose} // $self->_verbose;
191
192     my $filter = ( $method ) ? { plugin_method => $method } : undef;
193
194     my $plugin_classes = Koha::Plugins::Methods->search(
195         $filter,
196         {   columns  => 'plugin_class',
197             distinct => 1
198         }
199     )->_resultset->get_column('plugin_class');
200
201     my @plugins;
202
203     # Loop through all plugins that implement at least a method
204     while ( my $plugin_class = $plugin_classes->next ) {
205
206         if ( can_load( modules => { $plugin_class => undef }, verbose => $verbose, nocache => 1 ) ) {
207
208             my $plugin;
209             my $failed_instantiation;
210
211             try {
212                 $plugin = $plugin_class->new({
213                     enable_plugins => $self->{'enable_plugins'}
214                         # loads even if plugins are disabled
215                         # FIXME: is this for testing without bothering to mock config?
216                 });
217             }
218             catch {
219                 warn "$_";
220                 $failed_instantiation = 1;
221             };
222
223             next if $failed_instantiation;
224
225             next unless $plugin->is_enabled or
226                         defined($params->{all}) && $params->{all};
227
228             # filter the plugin out by metadata
229             my $plugin_metadata = $plugin->get_metadata;
230             next
231                 if $plugin_metadata
232                 and %$req_metadata
233                 and any { !$plugin_metadata->{$_} || $plugin_metadata->{$_} ne $req_metadata->{$_} } keys %$req_metadata;
234
235             push @plugins, $plugin;
236         } elsif ( defined($params->{errors}) && $params->{errors} ){
237             push @plugins, { error => 'cannot_load', name => $plugin_class };
238         }
239
240     }
241
242     return @plugins;
243 }
244
245 =head2 InstallPlugins
246
247 Koha::Plugins::InstallPlugins( [ verbose => 1 ] )
248
249 This method iterates through all plugins physically present on a system.
250 For each plugin module found, it will test that the plugin can be loaded,
251 and if it can, will store its available methods in the plugin_methods table.
252
253 NOTE: We reload all plugins here as a protective measure in case someone
254 has removed a plugin directly from the system without using the UI
255
256 =cut
257
258 sub InstallPlugins {
259     my ( $self, $params ) = @_;
260     my $verbose = $params->{verbose} // $self->_verbose;
261
262     my @plugin_classes = $self->plugins();
263     my @plugins;
264
265     foreach my $plugin_class (@plugin_classes) {
266         if ( can_load( modules => { $plugin_class => undef }, verbose => $verbose, nocache => 1 ) ) {
267             next unless $plugin_class->isa('Koha::Plugins::Base');
268
269             my $plugin;
270             my $failed_instantiation;
271
272             try {
273                 $plugin = $plugin_class->new({ enable_plugins => $self->{'enable_plugins'} });
274             }
275             catch {
276                 warn "$_";
277                 $failed_instantiation = 1;
278             };
279
280             next if $failed_instantiation;
281
282             Koha::Plugins::Methods->search({ plugin_class => $plugin_class })->delete();
283
284             foreach my $method ( @{ Class::Inspector->methods( $plugin_class, 'public' ) } ) {
285                 Koha::Plugins::Method->new(
286                     {
287                         plugin_class  => $plugin_class,
288                         plugin_method => $method,
289                     }
290                 )->store();
291             }
292
293             push @plugins, $plugin;
294         }
295     }
296
297     Koha::Cache::Memory::Lite->clear_from_cache(ENABLED_PLUGINS_CACHE_KEY);
298
299     return @plugins;
300 }
301
302 1;
303 __END__
304
305 =head1 AUTHOR
306
307 Kyle M Hall <kyle.m.hall@gmail.com>
308
309 =cut