#!/usr/bin/perlBEGIN{my$base_module_dir=(-d'/home/shlomif/perl'?'/home/shlomif/perl':(getpwuid($>))[7].'/perl/');unshift@INC,map{$base_module_dir.$_}@INC;}usestrict;usewarnings;useCGI::Minimal;useDBI;useEncodeqw(decode);useFile::Spec::Functionsqw( catpath splitpath rel2abs );binmodeSTDOUT,':encoding(utf8)';# We're using rand() later.srand();# The Directory containing the script.my$script_dir=catpath((splitpath(rel2abs$0))[0,1]);my$db_base_name="fortunes-shlomif-lookup.sqlite3";my$full_db_path="$script_dir/$db_base_name";my$dbh=DBI->connect("dbi:SQLite:dbname=$full_db_path","","");my$select_sth=$dbh->prepare(<<'EOF');SELECTf.text,f.title,c.str_id,c.titleFROMfortune_cookiesASf,fortune_collectionsAScWHERE((f.str_id=?)AND(f.collection_id=c.id))EOFmy$select_max_id=$dbh->prepare(q{SELECT MAX(id) FROM fortune_cookies});my$lookup_str_id_from_id=$dbh->prepare(q{SELECT str_id FROM fortune_cookies WHERE id = ?});my$cgi=CGI::Minimal->new;my$NL="\015\012";sub _header{print"Content-Type: text/html; charset=utf-8$NL$NL";return;}sub _emit_error{my($args)=@_;print"Status: 404 Not Found$NL";_header();_wrap_error_html($args);return;}sub _wrap_error_html{my($args)=@_;my$title=$args->{title};my$body=$args->{body};print<<"ERROR_HTML";<?xml version="1.0" encoding="utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US"><head><title>$title</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>$body</body></html>ERROR_HTML}my$mode=($cgi->param('mode')||'str_id');if($modeeq"random"){_pick_random();}elsif($modeeq"str_id"){my$str_id=$cgi->param('id');_show_by_str_id($str_id);}else{_invalid_mode($mode);}sub _invalid_mode{my($mode)=@_;my$mode_esc=$cgi->htmlize($mode);_emit_error({title=>qq{Error! Invalid mode "$mode_esc"},body=><<"END_OF_BODY",});<h1>Error!Invalidmode"$mode_esc".</h1><p>Onlyvalidmodesare<tt>random</tt>and<tt>str_id</tt>(where<tt>str_id</tt>isthedefault).</p>END_OF_BODYreturn;}sub _pick_random{my$rv=$select_max_id->execute();my($max_id)=$select_max_id->fetchrow_array;if(!$max_id){_emit_error({title=>"Query failed",body=><<"END_OF_BODY",});<h1>Queryfailed</h1><p>Reportthisproblemtothewebmaster.</p>END_OF_BODYreturn;}$rv=$lookup_str_id_from_id->execute(int(rand()*($max_id))+1);my($str_id)=$lookup_str_id_from_id->fetchrow_array();if(!$str_id){_emit_error({title=>q{Unknown fortune ID},body=><<'EOF'});<h1>lookup_str_id_from_idqueryfailed</h1><p>Reportthisproblemtothewebmaster.</p>EOFreturn;}# str_id must not contain any strange HTML/URI/etc. characters# If it does - then we suck.print"Location: ./show.cgi?id=$str_id$NL$NL";return;}sub _display_fortune_from_data{my($str_id,$html_text,$html_title,$col_str_id,$col_title)=@_;$html_text=decode('utf-8',$html_text);my$title_esc=$cgi->htmlize(decode('utf-8',$html_title))." - Fortune";_header();my$base_dir='../..';print<<"FORTUNE";<?xml version="1.0" encoding="utf-8"?><!DOCTYPEhtml PUBLIC "-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US"><head><title>$title_esc</title><link rel="stylesheet" href="$base_dir/fort_total.css" media="screen, projection" /><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body><ul id="nav"><li><a href="/">Shlomi Fish's Homepage</a></li><li><a href="./">Fortune Cookies Page</a></li><li><a href="${col_str_id}.html">@{[$cgi->htmlize($col_title)]}</a></li><li><a href="${col_str_id}.html#${str_id}">Fortune Cookie</a></li></ul><ul id="random"><li><a href="show.cgi?mode=random">Random Fortune</a></li></ul><h1>$title_esc</h1><div class="fortunes_list">$html_text</div></body></html>FORTUNEreturn;}sub _show_by_str_id{my($str_id)=@_;if(!$str_id){_emit_error({title=>q{ID parameter not specified},body=><<'END_OF_BODY'});<h1>Error!MustspecifyIDparameter</h1><p>TheIDparametermustbespecified.</p>END_OF_BODYreturn;}my$rv=$select_sth->execute($str_id);if(my@data=$select_sth->fetchrow_array){return_display_fortune_from_data($str_id,@data);}else{_emit_error({title=>q{URL not found},body=><<"END_OF_BODY"});<h1>URLnotfound</h1><p>ThefortuneID@{[$cgi->htmlize($str_id)]}isnotrecognised.Ifyou'vereachedthisURLandthinkitshouldbedefinedpleasecontact<ahref="mailto:shlomif\@shlomifish.org">ShlomiFish(theWebmaster)</a>andlethimknowofthisproblem.</p>END_OF_BODYreturn;}}__END__=head1 NAMEfortune_show.cgi - a Perl 5 , CGI.pm and L<DBD::SQLite> script to displaya fortune cookie.=head1 COPYRIGHT & LICENSECopyright 2011 by Shlomi Fish.This program is distributed under the MIT (X11) License:L<http://www.opensource.org/licenses/mit-license.php>Permission is hereby granted, free of charge, to any personobtaining a copy of this software and associated documentationfiles (the "Software"), to deal in the Software withoutrestriction, including without limitation the rights to use,copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom theSoftware is furnished to do so, subject to the followingconditions:The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIESOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHTHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISINGFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OROTHER DEALINGS IN THE SOFTWARE.=cut