Bug 29672: Increase performance of Koha::Plugins->call
[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 BEGIN {
38     my $pluginsdir = C4::Context->config("pluginsdir");
39     my @pluginsdir = ref($pluginsdir) eq 'ARRAY' ? @$pluginsdir : $pluginsdir;
40     push @INC, array_minus(@pluginsdir, @INC) ;
41     pop @INC if $INC[-1] eq '.';
42 }
43
44 =head1 NAME
45
46 Koha::Plugins - Module for loading and managing plugins.
47
48 =head2 new
49
50 Constructor
51
52 =cut
53
54 sub new {
55     my ( $class, $args ) = @_;
56
57     return unless ( C4::Context->config("enable_plugins") || $args->{'enable_plugins'} );
58
59     $args->{'pluginsdir'} = C4::Context->config("pluginsdir");
60
61     return bless( $args, $class );
62 }
63
64 =head2 call
65
66 Calls a plugin method for all enabled plugins
67
68     @responses = Koha::Plugins->call($method, @args)
69
70 Note: Pass your arguments as refs, when you want subsequent plugins to use the value
71 updated by preceding plugins, provided that these plugins support that.
72
73 =cut
74
75 sub call {
76     my ($class, $method, @args) = @_;
77
78     return unless C4::Context->config('enable_plugins');
79
80     my @responses;
81     my @plugins = $class->get_enabled_plugins();
82     @plugins = grep { $_->can($method) } @plugins;
83
84     # TODO: Remove warn when after_hold_create is removed from the codebase
85     warn "after_hold_create is deprecated and will be removed soon. Contact the following plugin's authors: " . join( ', ', map {$_->{metadata}->{name}} @plugins)
86         if $method eq 'after_hold_create' and @plugins;
87
88     foreach my $plugin (@plugins) {
89         my $response = eval { $plugin->$method(@args) };
90         if ($@) {
91             warn sprintf("Plugin error (%s): %s", $plugin->get_metadata->{name}, $@);
92             next;
93         }
94
95         push @responses, $response;
96     }
97
98     return @responses;
99 }
100
101 sub get_enabled_plugins {
102     my ($class) = @_;
103
104     return unless C4::Context->config('enable_plugins');
105
106     my $cache_key = 'enabled_plugins';
107     my $enabled_plugins = Koha::Cache::Memory::Lite->get_from_cache($cache_key);
108     unless ($enabled_plugins) {
109         $enabled_plugins = [];
110         my $rs = Koha::Database->schema->resultset('PluginData');
111         $rs = $rs->search({ plugin_key => '__ENABLED__', plugin_value => 1 });
112         my @plugin_classes = $rs->get_column('plugin_class')->all();
113         foreach my $plugin_class (@plugin_classes) {
114             unless (can_load(modules => { $plugin_class => undef }, nocache => 1)) {
115                 warn "Failed to load $plugin_class: $Module::Load::Conditional::ERROR";
116                 next;
117             }
118
119             my $plugin = eval { $plugin_class->new() };
120             if ($@ || !$plugin) {
121                 warn "Failed to instantiate plugin $plugin_class: $@";
122                 next;
123             }
124
125             push @$enabled_plugins, $plugin;
126         }
127         Koha::Cache::Memory::Lite->set_in_cache($cache_key, $enabled_plugins);
128     }
129
130     return @$enabled_plugins;
131 }
132
133 =head2 GetPlugins
134
135 This will return a list of all available plugins, optionally limited by
136 method or metadata value.
137
138     my @plugins = Koha::Plugins::GetPlugins({
139         method => 'some_method',
140         metadata => { some_key => 'some_value' },
141     });
142
143 The method and metadata parameters are optional.
144 If you pass multiple keys in the metadata hash, all keys must match.
145
146 =cut
147
148 sub GetPlugins {
149     my ( $self, $params ) = @_;
150
151     my $method       = $params->{method};
152     my $req_metadata = $params->{metadata} // {};
153
154     my $filter = ( $method ) ? { plugin_method => $method } : undef;
155
156     my $plugin_classes = Koha::Plugins::Methods->search(
157         $filter,
158         {   columns  => 'plugin_class',
159             distinct => 1
160         }
161     )->_resultset->get_column('plugin_class');
162
163     my @plugins;
164
165     # Loop through all plugins that implement at least a method
166     while ( my $plugin_class = $plugin_classes->next ) {
167
168         if ( can_load( modules => { $plugin_class => undef }, nocache => 1 ) ) {
169
170             my $plugin;
171             my $failed_instantiation;
172
173             try {
174                 $plugin = $plugin_class->new({
175                     enable_plugins => $self->{'enable_plugins'}
176                         # loads even if plugins are disabled
177                         # FIXME: is this for testing without bothering to mock config?
178                 });
179             }
180             catch {
181                 warn "$_";
182                 $failed_instantiation = 1;
183             };
184
185             next if $failed_instantiation;
186
187             next unless $plugin->is_enabled or
188                         defined($params->{all}) && $params->{all};
189
190             # filter the plugin out by metadata
191             my $plugin_metadata = $plugin->get_metadata;
192             next
193                 if $plugin_metadata
194                 and %$req_metadata
195                 and any { !$plugin_metadata->{$_} || $plugin_metadata->{$_} ne $req_metadata->{$_} } keys %$req_metadata;
196
197             push @plugins, $plugin;
198         } elsif ( defined($params->{errors}) && $params->{errors} ){
199             push @plugins, { error => 'cannot_load', name => $plugin_class };
200         }
201
202     }
203
204     return @plugins;
205 }
206
207 =head2 InstallPlugins
208
209 Koha::Plugins::InstallPlugins()
210
211 This method iterates through all plugins physically present on a system.
212 For each plugin module found, it will test that the plugin can be loaded,
213 and if it can, will store its available methods in the plugin_methods table.
214
215 NOTE: We reload all plugins here as a protective measure in case someone
216 has removed a plugin directly from the system without using the UI
217
218 =cut
219
220 sub InstallPlugins {
221     my ( $self, $params ) = @_;
222
223     my @plugin_classes = $self->plugins();
224     my @plugins;
225
226     foreach my $plugin_class (@plugin_classes) {
227         if ( can_load( modules => { $plugin_class => undef }, nocache => 1 ) ) {
228             next unless $plugin_class->isa('Koha::Plugins::Base');
229
230             my $plugin;
231             my $failed_instantiation;
232
233             try {
234                 $plugin = $plugin_class->new({ enable_plugins => $self->{'enable_plugins'} });
235             }
236             catch {
237                 warn "$_";
238                 $failed_instantiation = 1;
239             };
240
241             next if $failed_instantiation;
242
243             Koha::Plugins::Methods->search({ plugin_class => $plugin_class })->delete();
244
245             foreach my $method ( @{ Class::Inspector->methods( $plugin_class, 'public' ) } ) {
246                 Koha::Plugins::Method->new(
247                     {
248                         plugin_class  => $plugin_class,
249                         plugin_method => $method,
250                     }
251                 )->store();
252             }
253
254             push @plugins, $plugin;
255         } else {
256             my $error = $Module::Load::Conditional::ERROR;
257             # Do not warn the error if the plugin has been uninstalled
258             warn $error unless $error =~ m|^Could not find or check module '$plugin_class'|;
259         }
260     }
261     return @plugins;
262 }
263
264 1;
265 __END__
266
267 =head1 AUTHOR
268
269 Kyle M Hall <kyle.m.hall@gmail.com>
270
271 =cut