lib/MKDoc/Core/Plugin.pm

filter: Statementstmt 33.3% 1 / 3 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 1 / 1 Podpod n/a totaltotal 50.0% 2 / 4 CC 1 SCAR 2.6
CC
1
Cov
33%
BEGIN
1.3
CRAP 1.3
« blib/lib/MKDoc/Core/Plugin/Resources.pm ↑ Summary lib/MKDoc/Core/Request.pm »
1 =head1 NAME
2  
3 MKDoc::Core::Plugin - Class for atomic MKDoc application functionality
4  
5  
6 =head1 SUMMARY
7  
8 The L<MKDoc::Core> plugin system is a fundamental foundation for any application
9 which uses the L<MKDoc::Core> framework. Plugins are classes which are executed
10 one after the other in a predefined order.
11  
12 The plugin processor (MKDoc::process) executes a list of plugins until one
13 (usually the one which handles the request) returns 'TERMINATE'.
14  
15 =cut
16 package MKDoc::Core::Plugin;
17 0 ▶use MKDoc::Core::Request;
Subroutine BEGIN: called CC=1 SCAR=2.6
18 use MKDoc::Core::Response;
19 use MKDoc::Core::Language;
20 use MKDoc::Core::Error;
21 use Petal;
22 use URI;
23 use strict;
24 use warnings;
25  
26  
27 sub _used_once { $::MKD_Current_Plugin };
28  
29  
30  
31 =head1 Petal modifiers
32  
33 =head2 plugin:
34  
35 Instanciates a plugin of class plugin_type and returns it. This is handy if
36 you need to access the attributes methods of another plugin from the plugin
37 you're on, e.g:
38  
39 petal:define="details flo::plugin::Account::Details"
40  
41 =cut
42 $Petal::Hash::MODIFIERS->{'plugin:'} = sub {
43 my $hash = shift;
44 my $class = shift;
45 my $file = $class;
46 $file =~ s/::/\//g;
47 $file .= '.pm';
48  
49 for (@INC)
50 {
51 (-e "$_/$file") and do {
52 require $file;
53 last;
54 };
55 }
56  
57 return unless defined $INC{$file};
58 return eval "$class->new()";
59 };
60  
61  
62  
63 =head2 global:
64  
65 Gives you access to any scalar variable stored in $::.
66 For example:
67  
68 petal:define="site_dir global: MKD__SITE_DIR"
69  
70 =cut
71 $Petal::Hash::MODIFIERS->{'global:'} = sub {
72 my $hash = shift;
73 my $sym = shift;
74 return $ {$::{$sym}};
75 };
76  
77  
78  
79 =head1 Methods
80  
81 =head2 $self->equals ($otherplugin);
82  
83 Returns TRUE if the class of $self is the same as the class of $otherplugin.
84  
85 Since by default plugin objects do not have any data a class equivalence makes
86 sense, however this behavior can be subclassed as necessary.
87  
88 =cut
89 sub equals
90 {
91 my $self = shift;
92 my $thing = shift;
93 return ref $self eq ref $thing;
94 }
95  
96  
97  
98 =head2 $self->would_activate();
99  
100 Returns TRUE if this plugin would activate if it was requested.
101 Returns FALSE otherwise.
102  
103 For example:
104  
105 <span
106 petal:define="details flo::plugin::Account::Details"
107 petal:condition="details/would_activate"
108 > ./.account.details can be accessed from here!</span>
109  
110 For convenience, would_activate always returns FALSE if invoked on the same
111 class of plugin that is currently being activated. This is because usually,
112 hyperlinking to yourself is rather useless.
113  
114 i.e. if you were using the piece of code above in the account details plugin
115 itself, details/would_activate would always return false.
116  
117 =cut
118 sub would_activate
119 {
120 my $self = shift;
121 return if ($self->is_current_plugin());
122  
123 my $class = ref $self || $self;
124  
125 # let's lie about what the path_info is...
126 my $path_info = $self->location();
127  
128 local *MKDoc::Core::Request::path_info;
129 *MKDoc::Core::Request::path_info = sub { $path_info };
130  
131 # go through plugin list and see if $self activates
132 for (MKDoc::Core->plugin_list()) { return 1 if ($_ eq $class and $self->activate()) }
133  
134 return;
135 }
136  
137  
138  
139 =head2 $thing->current_plugin();
140  
141 Returns the current plugin which is being executed.
142  
143 =cut
144 sub current_plugin
145 {
146 return $::MKD_Current_Plugin;
147 }
148  
149  
150  
151 =head2 $self->is_current_plugin();
152  
153 Returns TRUE if $self is the plugin being currently executed, FALSE otherwise.
154  
155 =cut
156 sub is_current_plugin
157 {
158 my $self = shift;
159 return $self->equals ($self->current_plugin());
160 }
161  
162  
163  
164 =head2 $self->main();
165  
166 This class method is called by the MKDoc module.
167 Unless overriden it instantiates the current plugin and
168 checks to see if it should be activated. If so it processes
169 the request by calling run(), otherwise it does nothing.
170  
171 Returns 'TERMINATE' if the request was handled by this plugin,
172 false if not, or undef on error.
173  
174 =cut
175 sub main
176 {
177 my $class = shift || return;
178 my $self = $class->new (@_);
179 return ($self->activate) ? do {
180 local $MKDoc::Core::Error::CALLBACK;
181 $::MKDoc::Core::Error::CALLBACK = sub { $self->add_error (@_) };
182 $self->run();
183 } : undef;
184 }
185  
186  
187  
188 =head2 $class->new();
189  
190 Very basic constructor which instantiates a new object.
191 Calls the _initialize method.
192  
193 =cut
194 sub new
195 {
196 my $class = shift;
197 $class = ref $class || $class;
198 my $self = bless { @_ }, $class;
199 $self->_initialize;
200 return $self;
201 }
202  
203  
204  
205 =head2 $self->_initialize();
206  
207 Initializes this object, called by new(). This is empty, and
208 here to be overrided if necessary. Returns $self, or undef on
209 failure.
210  
211 =cut
212 sub _initialize
213 {
214 my $self = shift;
215 return $self;
216 }
217  
218  
219  
220 =head2 $self->run();
221  
222 Runs the current plugin. If the request is a POST, runs
223 $self->http_post(). If it's a GET, runs $self->http_get().
224  
225 =cut
226 sub run
227 {
228 my $self = shift;
229 my $meth = $self->request()->method();
230 if ($meth =~ /^POST$/) { $self->http_post (@_) }
231 else { $self->http_get (@_) }
232 }
233  
234  
235 =head2 $self->http_get();
236  
237 Processes an HTTP GET request.
238  
239 =cut
240 sub http_get
241 {
242 my $self = shift;
243 $self->render_http (
244 self => $self,
245 __input__ => 'XML',
246 __output__ => 'XHTML',
247 );
248 return 'TERMINATE';
249 }
250  
251  
252 =head2 $self->http_post();
253  
254 Processes an HTTP POST request.
255 Defaults http_get() by default.
256  
257 =cut
258 sub http_post
259 {
260 my $self = shift;
261 return $self->http_get (@_);
262 }
263  
264  
265  
266 =head2 $self->activate();
267  
268 Returns TRUE if this plugin wants to be activated, FALSE otherwise.
269  
270 By default it returns true if $self->location() equals the current
271 PATH_INFO.
272  
273 =cut
274 sub activate
275 {
276 my $self = shift;
277 my $location = $self->location() || '';
278 my $path_info = $self->request()->path_info() || '';
279 return $location eq $path_info;
280 }
281  
282  
283  
284 =head2 $self->uri();
285  
286 By default, returns the L<URI> of the current plugin without any parameters.
287 However, this behavior can be overriden as follows:
288  
289 # http://example.com/.plugin
290 $plugin->uri();
291
292 # http://example.com/.plugin?foo=bar
293 $plugin->uri (foo => 'bar');
294
295 # http://example.com/.plugin?keep-original=parameters
296 $plugin->uri ('parameters');
297
298 # http://example.com/.plugin?keep-original=parameters;foo=bar
299 $plugin->uri ( 'parameters', foo => 'bar');
300  
301 =cut
302 sub uri
303 {
304 my $self = shift;
305 my $req = $self->request->clone();
306  
307 if (defined $_[0] and $_[0] eq 'parameters')
308 {
309 shift (@_);
310 }
311 else
312 {
313 for ($req->param()) { $req->delete ($_) }
314 }
315  
316 while (@_)
317 {
318 my $key = shift;
319 my $val = shift;
320 $req->param ($key, "$val");
321 }
322  
323 $req->path_info ($self->location());
324 return URI->new ( $req->url ( -full => 1, -path => 1, -query => 1 ) );
325 }
326  
327  
328  
329 =head2 $self->uri_relative ($other);
330  
331 Same this object's URI relative to $other. $other can be a L<URI> object,
332 a SCALAR representing a URI, or an object which MUST have a uri() method.
333  
334 =cut
335 sub uri_relative
336 {
337 my $self = shift;
338 my $other_uri = shift;
339  
340 # if we already have a URI object, everything's good.
341 ref $other_uri and $other_uri->isa ('URI') and do {
342 return $self->uri()->rel ($other_uri);
343 };
344  
345 # if we have some kind of object that's not a URI, use
346 # $object->uri()
347 ref $other_uri and return $self->uri_relative ($other_uri->uri());
348  
349 # finally, we must have a scalar representing the URI...
350 return $self->uri_relative (URI->new ($other_uri));
351 }
352  
353  
354  
355 =head2 $self->language();
356  
357 Returns a L<MKDoc::Language> object which represents the preferred language
358 to be used for this plugin. By order of preference:
359  
360 =over
361  
362 =item looks into $ENV{HTTP_ACCEPT_LANGUAGE}
363  
364 =item looks at $ENV{MKD__DEFAULT_LANGUAGE}
365  
366 =item new MKDoc::Language ('en')
367  
368 =back
369  
370 =cut
371 sub language
372 {
373 my $self = shift;
374 $self->{'.language'} ||= do {
375 my $default = $ENV{MKD__DEFAULT_LANGUAGE} || 'en';
376 my $lang = $ENV{HTTP_ACCEPT_LANGUAGE} || '';
377  
378 $lang =~ s/^\s*//;
379 $lang =~ s/,.*$//;
380
381 new MKDoc::Core::Language ( $lang ) || new MKDoc::Core::Language ( $default );
382 };
383
384 return $self->{'.language'};
385 }
386  
387  
388  
389 =head2 $self->HTTP_Content_Type();
390  
391 Returns the content-type associated with this plugin.
392 By default, returns "text/html; charset=UTF-8"
393  
394 =cut
395 sub HTTP_Content_Type { "text/html; charset=UTF-8" }
396  
397  
398  
399 =head2 $self->has_errors();
400  
401 Returns TRUE if the current plugin object holds error that needs
402 to be displayed, false otherwise.
403  
404 =cut
405 sub has_errors
406 {
407 my $self = shift;
408 my $errors = $self->errors;
409 return scalar @{$errors};
410 }
411  
412  
413  
414 =head2 $self->errors();
415  
416 Returns a list of errors, or an array ref in scalar context.
417  
418 =cut
419 sub errors
420 {
421 my $self = shift;
422 return (defined $self->{'.errors'}) ?
423 $self->{'.errors'} :
424 [];
425 }
426  
427  
428  
429 =head2 $self->add_error (@_);
430  
431 Adds all the errors in @_ to the current plugin object.
432  
433 =cut
434 sub add_error
435 {
436 my $self = shift;
437 $self->{'.errors'} ||= [];
438 push @{$self->{'.errors'}}, @_;
439 }
440  
441  
442  
443 =head2 $self->render_http
444  
445 Renders the current object with render().
446 Sets the response object.
447  
448 Explores all the inherited HTTP_ methods and sets
449 HTTP headers accordingly.
450  
451 =cut
452 sub render_http
453 {
454 my $self = shift || return;
455 my $data = $self->render (@_) || return;
456 my $resp = $self->response();
457  
458 use bytes;
459 $resp->Body ($data);
460  
461 foreach my $method ( $self->_render_http_headers )
462 {
463 my $set_method = $method;
464 $set_method =~ s/^HTTP_//;
465  
466 my $del_method = "delete_$set_method";
467  
468 my $value = $self->$method();
469 if (defined $value) { $resp->$set_method ($value) }
470 else { $resp->$del_method() }
471 }
472
473 $resp->out();
474 }
475  
476  
477  
478 =head2 $this->_render_http_headers()
479  
480 Recursively introspects $this and its base classes and find
481 all methods which starts with HTTP_. Returns a list of methods
482 found.
483  
484 This little hack is written so that you can simply add HTTP
485 headers by defining methods, e.g.
486  
487 sub HTTP_X_Bender { "Bite my shiny, metal ass!" }
488  
489 Will set the following header:
490  
491 X-Bender: Bite my shiny, metal ass!
492  
493 =cut
494 sub _render_http_headers
495 {
496 my $class = shift;
497 $class = ref $class || $class;
498  
499 my %refs = do {
500 no strict 'refs';
501 map { $_ => 1 }
502 grep /^HTTP_/,
503 keys %{*{$class . "::"}}
504 };
505  
506 my %more_refs = do {
507 no strict 'refs';
508 map { $_ => 1 }
509 map { $_->_render_http_headers }
510 @{*{$class . "::ISA"}}
511 };
512  
513 my %result = (%refs, %more_refs);
514 return keys %result;
515 }
516  
517  
518  
519 =head2 $self->render (%args);
520  
521 Renders the current object, passing %args to the template being used.
522 Intercepts '__input__' and '__output__' to set Petal processing vars.
523  
524 Returns the rendered document on success, or undef on error.
525 See template_path().
526  
527 =cut
528 sub render
529 {
530 my $self = shift;
531 my $hash = (ref $_[0]) ? shift : { @_ };
532 $Petal::DISK_CACHE = 1;
533 $Petal::MEMORY_CACHE = 1;
534 $Petal::INPUT = $hash->{__input__} || 'XML';
535 $Petal::OUTPUT = $hash->{__output__} || 'XML';
536  
537 my $template = new Petal
538 language => $self->language()->code(),
539 file => $self->template_path();
540  
541 my $data = $template->process ( @_ );
542 return $data;
543 }
544  
545  
546  
547 =head2 $self->env()
548  
549 Returns the environment variables as a hash reference.
550  
551 =cut
552 sub env
553 {
554 my $self = shift;
555 return \%ENV;
556 }
557  
558  
559  
560 =head2 $self->env_keys();
561  
562 Returns the environment variables keys as an array or an array ref
563 depending on the context.
564  
565 =cut
566 sub env_keys
567 {
568 my $self = shift;
569 my @res = sort keys %ENV;
570 return wantarray ? @res : \@res;
571 }
572  
573  
574  
575 =head2 $self->env_value ($key);
576  
577 Returns the environment variable value for $key, i.e.
578  
579 my $path_info = $self->env_value ('PATH_INFO');
580  
581 =cut
582 sub env_value
583 {
584 my $self = shift;
585 my $key = shift;
586 return $ENV{$key};
587 }
588  
589  
590 =head2 $self->template_path();
591  
592 Returns the template path relative to Petal @BASE_DIR directories.
593  
594 By default if your plugin is called something like:
595  
596 Foo::Bar::Plugin::Hello::World
597  
598 It will return:
599  
600 /hello/world/
601  
602 This method is subclassable.
603  
604 =cut
605 sub template_path
606 {
607 my $self = shift;
608 my $class = ref $self || $self;
609 $class =~ s/MKDoc:://;
610 $class =~ s/Plugin:://;
611 $class = lc ($class);
612 $class =~ s/::/\//g;
613 return "/$class/";
614 }
615  
616  
617  
618 =head2 $self->location();
619  
620 Returns the location of the current plugin. By default, returns
621 the current PATH_INFO.
622  
623 =cut
624 sub location
625 {
626 my $self = shift;
627 return $self->request()->path_info();
628 }
629  
630  
631  
632 =head2 $self->request();
633  
634 Returns the MKDoc::Core::Request object singleton.
635  
636 =cut
637 sub request
638 {
639 return MKDoc::Core::Request->instance();
640 }
641  
642  
643  
644 =head2 $self->response();
645  
646 Returns the MKDoc::Core::Response object singleton.
647  
648 =cut
649 sub response
650 {
651 return MKDoc::Core::Response->instance();
652 }
653  
654  
655  
656 =head2 $self->return_uri();
657  
658 Some plugins have a need to redirect to a return uri once they have finished
659 processing. This is usually the case with POST request. This method tries to
660 provide a sensible default:
661  
662 =over 4
663  
664 =item it looks for a return_uri parameter
665  
666 =item otherwise it looks in $ENV{HTTP_REFERER}
667  
668 =item otherwise it returns the root of the website by setting path_info to '/'.
669  
670 =back
671  
672 =cut
673 sub return_uri
674 {
675 my $self = shift;
676 my $req = $self->request()->clone();
677 return $req->param ('return_uri') || $ENV{HTTP_REFERER} || do {
678 $req->path_info ('/');
679 $req->delete ($_) for ($req->param());
680 $req->self_uri();
681 };
682 }
683  
684  
685 1;
686  
687  
688 __END__
« blib/lib/MKDoc/Core/Plugin/Resources.pm ↑ Summary lib/MKDoc/Core/Request.pm »