home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_ste.zip / HTTP / Negotiate.pm < prev    next >
Text File  |  1997-04-03  |  16KB  |  506 lines

  1. # $Id: Negotiate.pm,v 1.6 1997/04/03 10:51:14 aas Exp $
  2. #
  3.  
  4. package HTTP::Negotiate;
  5.  
  6. $VERSION = sprintf("%d.%02d", q$Revision: 1.6 $ =~ /(\d+)\.(\d+)/);
  7. sub Version { $VERSION; }
  8.  
  9. require 5.002;
  10. require Exporter;
  11. @ISA = qw(Exporter);
  12. @EXPORT = qw(choose);
  13.  
  14. require HTTP::Headers;
  15.  
  16. $DEBUG = 0;
  17.  
  18. sub choose ($;$)
  19. {
  20.     my($variants, $request) = @_;
  21.     my(%accept);
  22.  
  23.     unless (defined $request) {
  24.     # Create a request object from the CGI envirionment variables
  25.     $request = new HTTP::Headers;
  26.     $request->header('Accept', $ENV{HTTP_ACCEPT})
  27.       if $ENV{HTTP_ACCEPT};
  28.     $request->header('Accept-Charset', $ENV{HTTP_ACCEPT_CHARSET})
  29.       if $ENV{HTTP_ACCEPT_CHARSET};
  30.     $request->header('Accept-Encoding', $ENV{HTTP_ACCEPT_ENCODING})
  31.       if $ENV{HTTP_ACCEPT_ENCODING};
  32.     $request->header('Accept-Language', $ENV{HTTP_ACCEPT_LANGUAGE})
  33.       if $ENV{HTTP_ACCEPT_LANGUAGE};
  34.     }
  35.  
  36.     # Get all Accept values from the request.  Build a hash initialized
  37.     # like this:
  38.     #
  39.     #   %accept = ( type =>     { 'audio/*'     => { q => 0.2, mbx => 20000 },
  40.     #                             'audio/basic' => { q => 1 },
  41.     #                           },
  42.     #               language => { 'no'          => { q => 1 },
  43.     #                           }
  44.     #             );
  45.  
  46.     $request->scan(sub {
  47.     my($key, $val) = @_;
  48.     return unless $key =~ s/^Accept-?//;
  49.     my $type = lc $key;
  50.     $type = "type" unless length $key;
  51.     $val =~ s/\s+//g;
  52.     my $name;
  53.     for $name (split(/,/, $val)) {
  54.         my(%param, $param);
  55.         if ($name =~ s/;(.*)//) {
  56.         for $param (split(/;/, $1)) {
  57.             my ($pk, $pv) = split(/=/, $param, 2);
  58.             $param{$pk} = $pv;
  59.         }
  60.         }
  61.         $name = lc $name;
  62.         if (defined $param{'q'}) {
  63.         $param{'q'} = 1 if $param{'q'} > 1;
  64.         $param{'q'} = 0 if $param{'q'} < 0;
  65.         } else {
  66.         $param{'q'} = 1;
  67.         }
  68.  
  69.         $param{'q'} = 1 unless defined $param{'q'};
  70.         $accept{$type}{$name} = \%param;
  71.     }
  72.     });
  73.  
  74.     # Check if any of the variants specify a language.  We do this
  75.     # because it influence how we treat those without (they default to
  76.     # 0.5 instead of 1).
  77.     my $any_lang = 0;
  78.     for $var (@$variants) {
  79.     if ($var->[5]) {
  80.         $any_lang = 1;
  81.         last;
  82.     }
  83.     }
  84.  
  85.     if ($DEBUG) {
  86.     print "Netgotiantion parameters in the request\n";
  87.     for $type (keys %accept) {
  88.         print " $type:\n";
  89.         for $name (keys %{$accept{$type}}) {
  90.         print "    $name\n";
  91.         for $pv (keys %{$accept{$type}{$name}}) {
  92.             print "      $pv = $accept{$type}{$name}{$pv}\n";
  93.         }
  94.         }
  95.     }
  96.     }
  97.  
  98.     my @Q = ();  # This is where we collect the results of the
  99.          # quality calcualtions
  100.  
  101.     # Calculate quality for all the variant's that are available.
  102.     for (@$variants) {
  103.     my($id, $qs, $ct, $enc, $cs, $lang, $bs) = @$_;
  104.     $qs = 1 unless defined $qs;
  105.     $bs = 0 unless defined $bs;
  106.     if ($DEBUG) {
  107.         print "\nEvaluating $id ($ct)\n";
  108.         printf "  qs   = %.3f\n", $qs;
  109.         print  "  enc  = $enc\n"  if $enc && !ref($enc);
  110.         print  "  enc  = @$enc\n" if $enc && ref($enc);
  111.         print  "  cs   = $cs\n"   if $cs;
  112.         print  "  lang = $lang\n" if $lang;
  113.         print  "  bs   = $bs\n"   if $bs;
  114.     }
  115.  
  116.     # Calculate encoding quality
  117.     my $qe = 1;
  118.     # If the variant has no assignes Content-Encoding, or if no
  119.     # Accept-Encoding field is present, then the value assigned
  120.     # is "qe=1".  If *all* of the variant's content encoddings
  121.     # are listed in the Accept-Encoding field, then the value
  122.     # assigned is "qw=1".  If *any* of the variant's content
  123.     # encodings are not listed in the provided Accept-Encoding
  124.     # field, then the value assigned is "qe=0"
  125.     if (exists $accept{'encoding'} && $enc) {
  126.         my @enc = ref($enc) ? @$enc : ($enc);
  127.         for (@enc) {
  128.         print "Is encoding $_ accepted? " if $DEBUG;
  129.         unless(exists $accept{'encoding'}{$_}) {
  130.             print "no\n" if $DEBUG;
  131.             $qe = 0;
  132.             last;
  133.         } else {
  134.             print "yes\n" if $DEBUG;
  135.         }
  136.         }
  137.     }
  138.  
  139.     # Calculate charset quality
  140.     my $qc  = 1;
  141.     # If the variant's media-type has not charset parameter,
  142.     # or the variant's charset is US-ASCII, or if no Accept-Charset
  143.     # field is present, then the value assigned is "qc=1".  If the
  144.     # variantµs charset is listed in the Accept-Charset field,
  145.     # then the value assigned is "qc=1.  Otherwise, if the variant's
  146.     # charset is not listed in the provided Accept-Encoding field,
  147.     # then the value assigned is "qc=0".
  148.     if (exists $accept{'charset'} && $cs && $cs ne 'us-ascii' ) {
  149.         $qc = 0 unless $accept{'charset'}{$cs};
  150.     }
  151.  
  152.     # Calculate language quality
  153.     my $ql  = 1;
  154.     if ($lang && exists $accept{'language'}) {
  155.         my @lang = ref($lang) ? @$lang : ($lang);
  156.         # If any of the variant's content languages are listed
  157.         # in the Accept-Language field, the the value assigned is
  158.         # the maximus of the "q" paramet values for thos language
  159.         # tags.
  160.         my $q = undef;
  161.         for (@lang) {
  162.         next unless exists $accept{'language'}{$_};
  163.         my $this_q = $accept{'language'}{$_}{'q'};
  164.         $q = $this_q unless defined $q;
  165.         $q = $this_q if $this_q > $q;
  166.         }
  167.         unless (defined $q) {
  168.         # If there was no exact match and at least one of
  169.         # the Accept-Language field values is a complete
  170.         # subtag prefix of the content language tag(s), then
  171.         # the "q" parameter value of the largest matching
  172.         # prefix is used.
  173.         my $selected = undef;
  174.         for $al (keys %{ $accept{'language'} }) {
  175.             if (substr($lang, 0, length($al)) eq $al) {
  176.             $selected = $al unless defined $selected;
  177.             $selected = $al if length($al) > length($selected);
  178.             }
  179.         }
  180.         $q = $accept{'language'}{$selected}{'q'} if $selected;
  181.  
  182.         # If none of the variant's content language tags or
  183.         # tag prefixes are listed in the provided
  184.         # Accept-Language field, then the value assigned
  185.         # is "ql=0.001"
  186.         $q = 0.001 unless defined $q;
  187.         }
  188.         $ql = $q;
  189.     } else {
  190.         $ql = 0.5 if $any_lang && exists $accept{'language'};
  191.     }
  192.  
  193.     my $q   = 1;
  194.     my $mbx = undef;
  195.     # If no Accept field is given, then the value assigned is "q=1".
  196.     # If at least one listed media range matches the variant's media
  197.     # type, then the "q" parameter value assigned to the most specific
  198.     # of those matched is used (e.g. "text/html;version=3.0" is more
  199.     # specific than "text/html", which is more specific than "text/*",
  200.     # which in turn is more specific than "*/*"). If not media range
  201.     # in the provided Accept field matches the variant's media type,
  202.     # then the value assigned is "q=0".
  203.     if (exists $accept{'type'} && $ct) {
  204.         # First we clean up our content-type
  205.         $ct =~ s/\s+//g;
  206.         my $params = "";
  207.         $params = $1 if $ct =~ s/;(.*)//;
  208.         my($type, $subtype) = split("/", $ct, 2);
  209.         my %param = ();
  210.         for $param (split(/;/, $params)) {
  211.         my($pk,$pv) = split(/=/, $param, 2);
  212.         $param{$pk} = $pv;
  213.         }
  214.  
  215.         my $sel_q = undef;
  216.         my $sel_mbx = undef;
  217.         my $sel_specificness = 0;
  218.  
  219.         ACCEPT_TYPE:
  220.         for $at (keys %{ $accept{'type'} }) {
  221.         print "Consider $at...\n" if $DEBUG;
  222.         my($at_type, $at_subtype) = split("/", $at, 2);
  223.         # Is it a match on the type
  224.         next if $at_type    ne '*' && $at_type    ne $type;
  225.         next if $at_subtype ne '*' && $at_subtype ne $subtype;
  226.         my $specificness = 0;
  227.         $specificness++ if $at_type ne '*';
  228.         $specificness++ if $at_subtype ne '*';
  229.         # Let's see if content-type parameters also match
  230.         while (($pk, $pv) = each %param) {
  231.             print "Check if $pk = $pv is true\n" if $DEBUG;
  232.             next unless exists $accept{'type'}{$at}{$pk};
  233.             next ACCEPT_TYPE
  234.               unless $accept{'type'}{$at}{$pk} eq $pv;
  235.             print "yes it is!!\n" if $DEBUG;
  236.             $specificness++;
  237.         }
  238.         print "Hurray, type match with specificness = $specificness\n"
  239.           if $DEBUG;
  240.  
  241.         if (!defined($sel_q) || $sel_specificness < $specificness) {
  242.             $sel_q   = $accept{'type'}{$at}{'q'};
  243.             $sel_mbx = $accept{'type'}{$at}{'mbx'};
  244.             $sel_specificness = $specificness;
  245.         }
  246.         }
  247.         $q   = $sel_q || 0;
  248.         $mbx = $sel_mbx;
  249.     }
  250.  
  251.     my $Q;
  252.     if (!defined($mbx) || $mbx >= $bs) {
  253.         $Q = $qs * $qe * $qc * $ql * $q;
  254.     } else {
  255.         $Q = 0;
  256.         print "Variant's size is too large ==> Q=0\n" if $DEBUG;
  257.     }
  258.  
  259.     if ($DEBUG) {
  260.         $mbx = "undef" unless defined $mbx;
  261.         printf "Q=%.3f", $Q;
  262.         print "  (q=$q, mbx=$mbx, qe=$qe, qc=$qc, ql=$ql, qs=$qs)\n";
  263.     }
  264.  
  265.     push(@Q, [$id, $Q, $bs]);
  266.     }
  267.  
  268.  
  269.     @Q = sort { $b->[1] <=> $a->[1] || $a->[2] <=> $b->[2] } @Q;
  270.  
  271.     return @Q if wantarray;
  272.     return undef unless @Q;
  273.     return undef if $Q[0][1] == 0;
  274.     $Q[0][0];
  275. }
  276.  
  277. 1;
  278.  
  279. __END__
  280.  
  281.  
  282. =head1 NAME
  283.  
  284. choose - choose a variant of a document to serve (HTTP content negotiation)
  285.  
  286. =head1 SYNOPSIS
  287.  
  288.  use HTTP::Negotiate;
  289.  
  290.  #  ID       QS     Content-Type   Encoding Char-Set        Lang   Size
  291.  $variants =
  292.   [['var1',  1.000, 'text/html',   undef,   'iso-8859-1',   'en',   3000],
  293.    ['var2',  0.950, 'text/plain',  'gzip',  'us-ascii',     'no',    400],
  294.    ['var3',  0.3,   'image/gif',   undef,   undef,          undef, 43555],
  295.   ];
  296.  
  297.  @prefered = choose($variants, $request_headers);
  298.  $the_one  = choose($variants);
  299.  
  300. =head1 DESCRIPTION
  301.  
  302. This module provide a complete implementation of the HTTP content
  303. negotiation algorithm specified in F<draft-ietf-http-v11-spec-00.ps>
  304. chapter 12.  Content negotiation allows for the selection of a
  305. preferred content representation based upon attributes of the
  306. negotiable variants and the value of the various Accept* header fields
  307. in the request.
  308.  
  309. The variants are ordered by preference by calling the function
  310. choose().
  311.  
  312. The first parameter is a description of the variants that we can
  313. choose among.  The variants are described by a reference to an array.
  314. Each element in this array is an array with the values [$id, $qs,
  315. $content_type, $content_encoding, $charset, $content_language,
  316. $content_length].  The meaning of these values are described
  317. below. The $content_encoding and $content_language can be either a
  318. single scalar value or an array reference if there are several values.
  319.  
  320. The second optional parameter is a reference to the request headers.
  321. This is used to look for "Accept*" headers.  You can pass a reference
  322. to either a HTTP::Request or a HTTP::Headers object.  If this
  323. parameter is missing, then the accept specification is initialized
  324. from the CGI environment variables HTTP_ACCEPT, HTTP_ACCEPT_CHARSET,
  325. HTTP_ACCEPT_ENCODING and HTTP_ACCEPT_LANGUAGE.
  326.  
  327. In array context, choose() returns a list of variant
  328. identifier/calculated quality pairs.  The values are sorted by
  329. quality, highest quality first.  If the calculated quality is the same
  330. for two variants, then they are sorted by size (smallest first). I<E.g.>:
  331.  
  332.   (['var1' => 1], ['var2', 0.3], ['var3' => 0]);
  333.  
  334. Note that also zero quality variants are included in the return list
  335. even if these should never be served to the client.
  336.  
  337. In scalar context, it returns the identifier of the variant with the
  338. highest score or C<undef> if none have non-zero quality.
  339.  
  340. If the $HTTP::Negotiate::DEBUG variable is set to TRUE, then a lot of
  341. noise is generated on STDOUT during evaluation of choose().
  342.  
  343. =head1 VARIANTS
  344.  
  345. A variant is described by a list of the following values.  If the
  346. attribute does not make sense or is unknown for a variant, then use
  347. C<undef> instead.
  348.  
  349. =over 3
  350.  
  351. =item identifier
  352.  
  353. This is just some string that you use as a name for the variant.  The
  354. identifier of the preferred variant is returned by choose().
  355.  
  356. =item qs
  357.  
  358. This is a number between 0.000 and 1.000 that describes the "source
  359. quality".  This is what F<draft-ietf-http-v11-spec-00.ps> says about this
  360. value:
  361.  
  362. Source quality is measured by the content provider as representing the
  363. amount of degradation from the original source.  For example, a
  364. picture in JPEG form would have a lower qs when translated to the XBM
  365. format, and much lower qs when translated to an ASCII-art
  366. representation.  Note, however, that this is a function of the source
  367. - an original piece of ASCII-art may degrade in quality if it is
  368. captured in JPEG form.  The qs values should be assigned to each
  369. variant by the content provider; if no qs value has been assigned, the
  370. default is generally "qs=1".
  371.  
  372. =item content-type
  373.  
  374. This is the media type of the variant.  The media type does not
  375. include a charset attribute, but might contain other parameters.
  376. Examples are:
  377.  
  378.   text/html
  379.   text/html;version=2.0
  380.   text/plain
  381.   image/gif
  382.   image/jpg
  383.  
  384. =item content-encoding
  385.  
  386. This is one or more content encodings that has been applied to the
  387. variant.  The content encoding is generally used as a modifier to the
  388. content media type.  The most common content encodings are:
  389.  
  390.   gzip
  391.   compress
  392.  
  393. =item content-charset
  394.  
  395. This is the character set used when the variant contains textual
  396. content.  The charset value should generally be C<undef> or one of these:
  397.  
  398.   us-ascii
  399.   iso-8859-1 ... iso-8859-9
  400.   iso-2022-jp
  401.   iso-2022-jp-2
  402.   iso-2022-kr
  403.   unicode-1-1
  404.   unicode-1-1-utf-7
  405.   unicode-1-1-utf-8
  406.  
  407. =item content-language
  408.  
  409. This describes one or more languages that are used in the variant.
  410. Language is described like this in F<draft-ietf-http-v11-spec-00.ps>: A
  411. language is in this context a natural language spoken, written, or
  412. otherwise conveyed by human beings for communication of information to
  413. other human beings.  Computer languages are explicitly excluded.
  414.  
  415. The language tags are the same as those defined by RFC-1766.  Examples
  416. are:
  417.  
  418.   no               Norwegian
  419.   en               International English
  420.   en-US            US English
  421.   en-cockney
  422.  
  423. =item content-length
  424.  
  425. This is the number of bytes used to represent the content.
  426.  
  427. =back
  428.  
  429. =head1 ACCEPT HEADERS
  430.  
  431. The following Accept* headers can be used for describing content
  432. preferences in a request (This description is an edited extract from
  433. F<draft-ietf-http-v11-spec-00.ps>):
  434.  
  435. =over 3
  436.  
  437. =item Accept
  438.  
  439. This header can be used to indicate a list of media ranges which are
  440. acceptable as a reponse to the request.  The "*" character is used to
  441. group media types into ranges, with "*/*" indicating all media types
  442. and "type/*" indicating all subtypes of that type.
  443.  
  444. The parameter q is used to indicate the quality factor, which
  445. represents the user's preference for that range of media types.  The
  446. parameter mbx gives the maximum acceptable size of the response
  447. content. The default values are: q=1 and mbx=infinity. If no Accept
  448. header is present, then the client accepts all media types with q=1.
  449.  
  450. For example:
  451.  
  452.   Accept: audio/*;q=0.2;mbx=200000, audio/basic
  453.  
  454. would mean: "I prefer audio/basic (of any size), but send me any audio
  455. type if it is the best available after an 80% mark-down in quality and
  456. its size is less than 200000 bytes"
  457.  
  458.  
  459. =item Accept-Charset
  460.  
  461. Used to indicate what character sets are acceptable for the response.
  462. The "us-ascii" character set is assumed to be acceptable for all user
  463. agents.  If no Accept-Charset field is given, the default is that any
  464. charset is acceptable.  Example:
  465.  
  466.   Accept-Charset: iso-8859-1, unicode-1-1
  467.  
  468.  
  469. =item Accept-Encoding
  470.  
  471. Restricts the Content-Encoding values which are acceptable in the
  472. response.  If no Accept-Encoding field is present, the server may
  473. assume that the client will accept any content encoding.  An empty
  474. Accept-Encoding means that no content encoding is acceptable.  Example:
  475.  
  476.   Accept-Encoding: compress, gzip
  477.  
  478.  
  479. =item Accept-Language
  480.  
  481. This field is similar to Accept, but restrict the set of natural
  482. languages that are preferred as a response.  Each language may be
  483. given an associated quality value which represents an estimate of the
  484. user's comprehension of that language.  For example:
  485.  
  486.   Accept-Language: no, en-gb;q=0.8, de;q=0.55
  487.  
  488. would mean: "I prefer Norwegian, but will accept British English (with
  489. 80% comprehension) or German (with 55% comprehension).
  490.  
  491. =back
  492.  
  493.  
  494. =head1 COPYRIGHT
  495.  
  496. Copyright 1996, Gisle Aas.
  497.  
  498. This library is free software; you can redistribute it and/or
  499. modify it under the same terms as Perl itself.
  500.  
  501. =head1 AUTHOR
  502.  
  503. Gisle Aas <aas@sn.no>
  504.  
  505. =cut
  506.