blib/lib/ASP4.pm

filter: Statementstmt 100% 8 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 100% 10 / 10 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/ASP4/SessionStateManager/NonPersisted.pm ↑ Summary blib/lib/ASP4/FormHandler.pm »
1  
2 package ASP4;
3  
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 our $VERSION = '1.087';
7  
8  
9 1 1;# return true:
10  
11 =pod
12  
13 =head1 NAME
14  
15 ASP4 - Fast, Simple and Scalable Web Development for Perl [DEPRECATED]
16  
17 =head1 DEPRECATED
18  
19 ASP4 has been deprecated as of 2012-05-07.
20  
21 =head1 DESCRIPTION
22  
23 ASP4 is a modern web development platform for Perl with a focus on speed, simplicity
24 and scalability.
25  
26 =head1 ASP OBJECTS
27  
28 ASP4 brings our old friends C<$Request>, C<$Response>, C<$Server> and C<$Session>
29 back from the 1990's, but adds some new ever-present objects as well. Together
30 the ASP objects provide a consistent interface to the incoming request, outgoing response,
31 server environment and configuration in-use by the application itself.
32  
33 =head2 $Form
34  
35 This is a simple hash reference which contains the names and values of the incoming
36 request parameters for both GET and POST requests.
37  
38 For example, the following request...
39  
40 /foo.asp?name=joe&color=red
41  
42 ...produces the following C<$Form> object:
43  
44 $VAR1 = {
45 name => 'joe',
46 color => 'red'
47 };
48  
49 Access form data just like any other hashref:
50  
51 Hello, <%= $Form->{name} %>, I see your favorite color is <%= $Form->{color} %>.
52  
53 =head2 $Server
54  
55 The C<$Server> object offers a few utility methods that don't really fit anywhere else.
56  
57 =head3 $Server->HTMLEncode( $string )
58  
59 Given a string like C<< <br/> >> returns a string like C<< &lt;br/&gt; >>
60  
61 =head3 $Server->HTMLDecode( $string )
62  
63 Given a string like C<< &lt;br/&gt; >> returns a string like C<< <br/> >>
64  
65 =head3 $Server->URLEncode( $string )
66  
67 Given a string like C<< billg@microsoft.com >> returns a string like C<< billg%40microsoft.com >>
68  
69 =head3 $Server->URLDecode( $string )
70  
71 Given a string like C<< billg%40microsoft.com >> returns a string like C<< billg@microsoft.com >>
72  
73 =head3 $Server->MapPath( $path )
74  
75 Given a C<$path> of C</foo.asp> would return something like C</var/www/example.com/htdocs/foo.asp>
76  
77 =head3 $Server->Mail( %args )
78  
79 Sends an email via L<Mail::Sendmail>. In fact it simply calls the C<sendmail(...)> function
80 provided by L<Mail::Sendmail>.
81  
82 Simple Example:
83  
84 $Server->Mail(
85 from => 'foo@bar.com',
86 to => 'bar@foo.com',
87 subject => 'Hello, world!',
88 message => 'this is a test message'
89 );
90  
91 To send an HTML email do the following:
92  
93 use MIME::Base64;
94 $Server->Mail(
95 from => 'foo@bar.com',
96 to => 'bar@foo.com',
97 subject => 'Hello, world!',
98 'content-type' => 'text/html',
99 'content-transfer-encoding' => 'base64',
100 message => encode_base64(<<"HTML")
101 <html>
102 <body>
103 <p>This is an html email.</p>
104 <p>You can see that <b>this text is bold</b>.</p>
105 </body>
106 </html>
107 HTML
108 );
109  
110 Please see L<Mail::Sendmail> for further details and examples.
111  
112 =head3 $Server->RegisterCleanup( sub { ... }, \@args )
113  
114 After the final response has been sent to the client, the server will execute
115 your subref and provide it the C<\@args> passed in.
116  
117 This is useful for long-running or asynchronous processes that don't require the
118 client to wait for a response.
119  
120 =head2 $Request
121  
122 An instance of L<ASP4::Request>, the C<$Request> object contains specialized methods
123 for dealing with whatever the browser sent us.
124  
125 Examples:
126  
127 =head3 $Request->Cookies( $name )
128  
129 my $cookie = $Request->Cookies("some-cookie-name");
130  
131 =head3 $Request->FileUpload( $field_name )
132  
133 if( my $file = $Request->FileUpload('avatar_pic') ) {
134 # Handle the uploaded file:
135 $file->SaveAs( "/var/media/$Session->{user_id}/avatar/" . $file->FileName );
136 }
137  
138 See also the L<ASP4::FileUpload> documentation.
139  
140 =head2 $Response
141  
142 An instance of L<ASP4::Response>, the C<$Response> object gives shortcuts for dealing
143 with the outgoing reply from the server back to the client.
144  
145 Examples:
146  
147 =head3 $Response->Write( $string )
148  
149 The following example prints the string C<Hello, World!> to the browser:
150  
151 $Response->Write("Hello, World!");
152  
153 Or, within an ASP script, C<< <%= "Hello, World" %> >>
154  
155 =head3 $Response->Redirect( $url )
156  
157 $Response->Redirect( "/new/url/?foo=bar" );
158  
159 =head3 $Response->SetCookie( %args )
160  
161 Setting cookies works as follows:
162  
163 $Response->SetCookie(
164 name => "cookie-name",
165 value => "the-value",
166
167 # The rest of these arguments are optional:
168
169 # Expires: (If you don't specify the "expires" argument, the cookie will
170 # be deleted when the browser is closed.
171 expires => "3D", # 3 days
172 expires => "3H", # or 3 hours
173 expires => "3M", # or 3 minutes
174
175 # Domain: (defaults to $ENV{HTTP_HOST})
176 domain => ".example.com", # works for *.example.com
177 domain => "www.example.com", # will ONLY work for www.example.com
178
179 # Path:
180 path => "/some/folder/" # will ONLY work within /some/folder/ on your website
181 );
182  
183 =head3 $Response->Include( $path, %args )
184  
185 ASP4's C<$Response> object offers 3 different include methods.
186  
187 <!-- Normal SSI-style Include -->
188 <!-- #include virtual="/includes/page.asp" -->
189  
190 If you want to supply arguments to the included ASP script you can use C<< $Response->Include($path, \%args) >>
191  
192 # Add the output of C</includes/page.asp> to the current output buffer:
193 my %args = ( foo => "bar" );
194 $Response->Include( $Server->MapPath("/includes/page.asp"), \%args );
195  
196 C<\%args> is optional.
197  
198 Within the included ASP script, C<\%args> is accessible like this:
199  
200 <%
201 my ($self, $context, $args) = @_;
202 %>
203  
204 =head3 $Response->TrapInclude( $path, %args )
205  
206 Or if you need to capture the result of executing an ASP script and use it within
207 a variable, use C<< $Response->TrapInclude($path, \%args) >>
208  
209 # Capture the output of C</includes/page.asp>:
210 my %args = ( foo => "bar" );
211 my $html = $Response->TrapInclude( $Server->MapPath("/includes/page.asp"), \%args );
212  
213 C<\%args> is optional.
214  
215 Within the included ASP script, C<\%args> is accessible like this:
216  
217 <%
218 my ($self, $context, $args) = @_;
219 %>
220  
221 =head2 $Session
222  
223 The C<$Session> object is an instance of a subclass of L<ASP4::SessionStateManager>
224 (depending on your website's configuration).
225  
226 The C<$Session> object is a simple blessed hashref and should be used like a hashref.
227  
228 Examples:
229  
230 =head3 Set a session variable
231  
232 $Session->{foo} = "bar";
233  
234 $Session->{thing} = {
235 banana => "yellow",
236 cherry => "red",
237 peach => "pink,
238 };
239  
240 =head3 Get a session variable
241  
242 my $foo = $Session->{foo};
243  
244 =head3 $Session->save()
245  
246 Called automatically at the end of every successful request, causes any changes
247 to the C<$Session> to be saved to the database.
248  
249 =head3 $Session->reset()
250  
251 Call C<< $Session->reset() >> to clear all the data out of the session and save
252 it to the database.
253  
254 =head2 $Config
255  
256 The ASP4 C<$Config> object is stored in a simple JSON format on disk, and accessible
257 everywhere within your entire ASP4 application as the global C<$Config> object.
258  
259 If ever you find yourself in a place without a C<$Config> object, you can get one
260 like this:
261  
262 use ASP4::ConfigLoader;
263 my $Config = ASP4::ConfigLoader->load();
264  
265 See L<ASP4::Config> for full details on the ASP4 C<$Config> object and its usage.
266  
267 =head2 $Stash
268  
269 The C<$Stash> is a simple hashref that is guaranteed to be the exact same hashref
270 throughout the entire lifetime of a request.
271  
272 Anything placed within the C<$Stash> at the very beginning of processing a request -
273 such as in a RequestFilter - will still be there at the very end of the request -
274 as in a RegisterCleanup handler.
275  
276 Use the C<$Stash> as a great place to store a piece of data for the duration of
277 a single request.
278  
279 =head1 DATABASE
280  
281 While ASP4 B<does not require> its users to choose any specific database (eg: MySQL or PostgreSQL)
282 or ORM (object-relational mapper) the B<recommended> ORM is L<Class::DBI::Lite>
283 since it has been completely and thoroughly tested to be 100% compatible with ASP4.
284  
285 For full documentation about L<Class::DBI::Lite> please view its documentation.
286  
287 B<NOTE:> L<Class::DBI::Lite> must be installed in addition to ASP4 as it is a separate library.
288  
289 =head1 ASP4 QuickStart
290  
291 Here is an example project to get things going.
292  
293 In the C<data_connections.main> section of C<conf/asp4-config.json> you should have
294 something like this:
295  
296 ...
297 "main": {
298 "dsn": "DBI:mysql:database_name:data.mywebsite.com",
299 "username": "db-username",
300 "password": "db-pAsswOrd"
301 }
302 ...
303  
304 Suppose you had the following tables in your database:
305  
306 create table users (
307 user_id bigint unsigned not null primary key auto_increment,
308 email varchar(200) not null,
309 password char(32) not null,
310 created_on timestamp not null default current_timestamp,
311 unique(email)
312 ) engine=innodb charset=utf8;
313
314 create table messages (
315 message_id bigint unsigned not null primary key auto_increment,
316 from_user_id bigint unsigned not null,
317 to_user_id bigint unsigned not null,
318 subject varchar(100) not null,
319 body text,
320 created_on timestamp not null default current_timestamp,
321 foreign key fk_messages_to_senders (from_user_id) references users (user_id) on delete cascade,
322 foreign key fk_messages_to_recipients (to_user_id) references users (user_id) on delete cascade
323 ) engine=innodb charset=utf8;
324  
325 B<NOTE:> It's best to assign every ASP4 application its own namespace. For this
326 example the namespace is C<App::db::>
327  
328 Create the file C<lib/App::db/model.pm> and add the following lines:
329  
330 package App::db::model;
331
332 use strict;
333 use warnings 'all';
334 use base 'Class::DBI::Lite::mysql';
335 use ASP4::ConfigLoader;
336
337 # Get our configuration object:
338 my $Config = ASP4::ConfigLoader->load();
339
340 # Get our main database connection info:
341 my $conn = $Config->data_connections->main;
342
343 # Setup our database connection:
344 __PACKAGE__->connection(
345 $conn->dsn,
346 $conn->username,
347 $conn->password
348 );
349
350 1;# return true:
351  
352 Add the following C<Class::DBI::Lite> entity classes:
353  
354 C<lib/App/db/user.pm>
355  
356 package App::db::user;
357
358 use strict;
359 use warnings 'all';
360 use base 'App::db::model';
361 use Digest::MD5 'md5_hex';
362 use ASP4::ConfigLoader;
363
364 __PACKAGE__->set_up_table('users');
365
366 __PACKAGE__->has_many(
367 messages_in =>
368 'App::db::message' =>
369 'to_user_id'
370 );
371
372 __PACKAGE__->has_many(
373 messages_out =>
374 'App::db::message' =>
375 'from_user_id'
376 );
377
378 # Hash the password before storing it in the database:
379 __PACKAGE__->add_trigger( before_create => sub {
380 my ($self) = @_;
381
382 # Sign the password instead of storing it as plaintext:
383 unless( $self->{password} =~ m{^([a-f0-9]{32})$}i ) {
384 $self->{password} = $self->hash_password( $self->password );
385 }
386 });
387
388 # Hash the new password before storing it in the database:
389 __PACKAGE__->add_trigger( before_update_password => sub {
390 my ($self, $old, $new) = @_;
391
392 unless( $new =~ m{^([a-f0-9]{32})$}i ) {
393 $self->{password} = $self->hash_password( $new );
394 }
395 });
396
397 # Verify an email/password combination and return the user if a match is found:
398 sub check_credentials {
399 my ($self, %args) = @_;
400
401 my ($result) = $self->search(
402 email => $args{email},
403 password => $self->hash_password( $args{password} ),
404 );
405
406 $result ? return $result : return;
407 }
408
409 # Convert a password string into its hashed value:
410 sub hash_password {
411 my ($self, $str) = @_;
412
413 my $key = ASP4::ConfigLoader->load->system->settings->signing_key;
414 return md5_hex( $str . $key );
415 }
416
417 1;# return true:
418  
419 C<lib/App/db/message.pm>
420  
421 package App::db::message;
422
423 use strict;
424 use warnings 'all';
425 use base 'App::db::model';
426
427 __PACKAGE__->set_up_table('messages');
428
429 __PACKAGE__->belongs_to(
430 sender =>
431 'App::db::user' =>
432 'from_user_id'
433 );
434
435 __PACKAGE__->belongs_to(
436 recipient =>
437 'App::db::user' =>
438 'to_user_id'
439 );
440
441 1;# return true:
442  
443 Create your MasterPage like this:
444  
445 File: C<htdocs/masters/global.asp>
446  
447 <%@ MasterPage %>
448 <!DOCTYPE html>
449 <html>
450 <head>
451 <title><asp:ContentPlaceHolder id="meta_title"></asp:ContentPlaceHolder></title>
452 <meta charset="utf-8" />
453 </head>
454 <body>
455 <h1><asp:ContentPlaceHolder id="headline"></asp:ContentPlaceHolder></h1>
456 <asp:ContentPlaceHolder id="main_content"></asp:ContentPlaceHolder>
457 </body>
458 </html>
459  
460 File: C<htdocs/index.asp>
461  
462 <%@ Page UseMasterPage="/masters/global.asp" %>
463
464 <asp:Content PlaceHolderID="meta_title">Register</asp:Content>
465
466 <asp:Content PlaceHolderID="headline">Register</asp:Content>
467
468 <asp:Content PlaceHolderID="main_content">
469 <%
470 # Sticky forms work like this:
471 if( my $args = $Session->{__lastArgs} ) {
472 map { $Form->{$_} = $args->{$_} } keys %$args;
473 }
474
475 # Our validation errors:
476 my $errors = $Session->{validation_errors} || { };
477 $::err = sub {
478 my $field = shift;
479 my $error = $errors->{$field} or return;
480 %><span class="field_error"><%= $Server->HTMLEncode( $error ) %></span><%
481 };
482 %>
483 <form id="register_form" method="post" action="/handlers/myapp.register">
484 <p>
485 <label>Email:</label>
486 <input type="text" name="email" value="<%= $Server->HTMLEncode( $Form->{email} ) %>" />
487 <% $::err->("email"); %>
488 </p>
489 <p>
490 <label>Password:</label>
491 <input type="password" name="password" />
492 <% $::err->("password"); %>
493 </p>
494 <p>
495 <label>Confirm Password:</label>
496 <input type="password" name="password2" />
497 <% $::err->("password2"); %>
498 </p>
499 <p>
500 <input type="submit" value="Register Now" />
501 </p>
502 </form>
503 </asp:Content>
504  
505 The form submits to the URL C</handlers/app.register> which means C<handlers/app/register.pm>
506  
507 File: C<handlers/app/register.pm>
508  
509 package app::register;
510
511 use strict;
512 use warnings 'all';
513 use base 'ASP4::FormHandler';
514 use vars __PACKAGE__->VARS; # Import $Response, $Form, $Session, etc
515 use App::db::user;
516
517 sub run {
518 my ($self, $context) = @_;
519
520 # If there is an error, return the user to the registration page:
521 if( my $errors = $self->validate() ) {
522 $Session->{validation_errors} = $errors;
523 $Session->{__lastArgs} = $Form;
524 $Session->save;
525 return $Response->Redirect( $ENV{HTTP_REFERER} );
526 }
527
528 # Create the user:
529 my $user = eval {
530 App::db::user->do_transaction(sub {
531 return App::db::user->create(
532 email => $Form->{email},
533 password => $Form->{password},
534 );
535 });
536 };
537
538 if( $@ ) {
539 # There was an error:
540 $Session->{validation_errors} = {email => "Server error. Sorry!"};
541 $Session->{__lastArgs} = $Form;
542 $Session->save;
543 return $Response->Redirect( $ENV{HTTP_REFERER} );
544 }
545 else {
546 # No error - Sign them in:
547 $Session->{user_id} = $user->id;
548 $Session->{msg} = "Thank you for registering!";
549 $Session->save;
550
551 # Redirect to /profile.asp:
552 return $Response->Redirect("/profile.asp");
553 }# end if()
554 }
555
556 sub validate {
557 my ($self) = @_;
558
559 $self->trim_form;
560
561 my $errors = { };
562 no warnings 'uninitialized';
563
564 # email:
565 if( length($Form->{email}) ) {
566 # Basic email validation:
567 unless( $Form->{email} =~ m{[^@]+@[^@]+\.[^@]+} ) {
568 $errors->{email} = "Invalid email address";
569 }
570 }
571 else {
572 $errors->{email} = "Required";
573 }
574
575 # password:
576 unless( length($Form->{password} ) {
577 $errors->{password} = "Required";
578 }
579
580 # password2:
581 if( length($Form->{password2}) ) {
582 if( length($Form->{password}) ) {
583 unless( $Form->{password} eq $Form->{password2} ) {
584 $errors->{password2} = "Passwords don't match";
585 }
586 }
587 }
588 else {
589 $errors->{password2} = "Required";
590 }
591
592 # Bail out of we already have errors:
593 return $errors if keys %$errors;
594
595 # See if the user already exists:
596 if( App::db::user->count_search( email => $Form->{email} ) ) {
597 $errors->{email} = "Already in use";
598 }
599
600 # Errors or not?:
601 keys %$errors ? return $errors : return;
602 }
603
604 1;# return true:
605  
606 File: C<htdocs/profile.asp>
607  
608 <%@ Page UseMasterPage="/masters/global.asp" %>
609
610 <asp:Content PlaceHolderID="meta_title">My Profile</asp:Content>
611
612 <asp:Content PlaceHolderID="headline">My Profile</asp:Content>
613
614 <asp:Content PlaceHolderID="main_content">
615 <%
616 if( my $msg = $Session->{msg} ) {
617 %>
618 <div class="message"><%= $msg %></div>
619 <%
620 }# end if()
621 %>
622
623 <%
624 # Get our $user:
625 use App::db::user;
626 my $user = App::db::user->retrieve( $Session->{user_id} );
627 %>
628
629 <div style="float: left; width: 40%; border-right: solid 1px #000;">
630 <h3>Incoming Messages</h3>
631 <%
632 foreach my $msg ( $user->messages_in(undef, { order_by => "created_on ASC"} ) ) {
633 %>
634 <div class="msg">
635 <span class="from"><%= $msg->sender->email %></span> says:<br/>
636 <div class="body"><%= $Server->HTMLEncode( $msg->body ) %></div>
637 <span class="date"><%= $msg->created_on %></span>
638 </div>
639 <%
640 }# end foreach()
641 %>
642 </div>
643
644 <div style="float: right; width: 40%; border: dotted 1px #000;">
645 <h3>Send New Message</h3>
646 <form id="send_form" method="post" action="/handlers/app.send">
647 <p>
648 <label>Recipient:</label>
649 <select name="to_user_id">
650 <%
651 my @users = App::db::user->search_where({
652 user_id => {'!=' => $user->id }
653 }, {
654 order_by => "email"
655 });
656 foreach my $user ( @users ) {
657 %>
658 <option value="<%= $user->id %>"><%= $Server->HTMLEncode( $user->email ) %></option>
659 <%
660 }# end foreach()
661 %>
662 </select>
663 </p>
664 <p>
665 <label>Subject:</label>
666 <input type="text" name="subject" maxlength="100" />
667 </p>
668 <p>
669 <label>Message:</label><br/>
670 <textarea name="body"></textarea>
671 </p>
672 <p>
673 <input type="submit" value="Send Message" />
674 </p>
675 </form>
676 </div>
677 </asp:Content>
678  
679 The form submits to C</handlers/app.send> which maps to C<handlers/app/send.pm>
680  
681 File: C<handlers/app/send.pm>
682  
683 package app::send;
684
685 use strict;
686 use warnings 'all';
687 use base 'ASP4::FormHandler';
688 use vars __PACKAGE__->VARS;
689 use App::db::user;
690 use App::db::message;
691
692 sub run {
693 my ($self, $context) = @_;
694
695 # Create the message:
696 my $msg = eval {
697 App::db::message->do_transaction(sub {
698 my $msg = App::db::message->create(
699 from_user_id => $Session->{user_id},
700 to_user_id => $Form->{to_user_id},
701 subject => $Form->{subject},
702 body => $Form->{body},
703 );
704
705 # Send an email to the recipient:
706 $Server->Mail(
707 from => 'root@localhost',
708 'reply-to' => $msg->sender->email,
709 to => $msg->recipient->email,
710 subject => 'New in-club message',
711 message => <<"MSG",
712 Dear user,
713
714 Another user (@{[ $msg->sender->email ]}) has sent you an in-club message.
715
716 Please login and view it on your profile at http://$ENV{HTTP_HOST}/
717
718 Yours,
719 The "In Club"
720 MSG
721 );
722
723 # Finally:
724 return $msg;
725 });
726 };
727
728 if( $@ ) {
729 $Session->{msg} = "Error: Your message could not be sent.";
730 $Session->save;
731 return $Response->Redirect( $ENV{HTTP_REFERER} );
732 }
733 else {
734 $Session->{msg} = "New message sent successfully.";
735 $Session->save;
736 return $Response->Redirect( $ENV{HTTP_REFERER} );
737 }
738 }
739  
740 =head1 BUGS
741  
742 It's possible that some bugs have found their way into this release.
743  
744 Use RT L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=ASP4> to submit bug reports.
745  
746 =head1 HOMEPAGE
747  
748 Please visit the ASP4 homepage at L<http://0x31337.org/code/> to see examples
749 of ASP4 in action.
750  
751 =head1 AUTHOR
752  
753 John Drago <jdrago_999@yahoo.com>
754  
755 =head1 COPYRIGHT
756  
757 This software is Free software and may be used and redistributed under the same
758 terms as perl itself.
759  
760 =cut
761  
« blib/lib/ASP4/SessionStateManager/NonPersisted.pm ↑ Summary blib/lib/ASP4/FormHandler.pm »