モバイル向け Google Adsense -言語比較が面白い-

恥ずかしながら本日、モバイルでも Google Adsense が始まったことを知りました。Adsense広告といえばJavaScriptと思っていたので、(JavaScript非対応機種の多い)モバイルで早期実現するとは思ってなかったので嬉しい驚きです。


さて、早速チェックしたところ(JavaScriptではなく)サーバーサイド言語による出力にのみ対応で、PHP, CGI/Perl, JSP, ASP の貼り付けソースコードが用意されています。(現時点では Ruby によるコードはなし)


90%の方は導入方法やクリック単価のことに興味があるのでしょうが、ここは Hatena Dairy。やっぱりコードですよ、コード。


「リモートサーバー上で広告を表示する」という同一の機能を実装するにあたって、PHP, Perl, JSP, ASP の4言語間で、コード量や可読性に大きな差があることが非常に興味深いです。


※ コードを読むと明らかですが、 PHPPerl, JSP, ASP と実装方法が異なるので、これをもって各言語を評価するのはよくないと思います。


1. PHP

<?php

$GLOBALS['google']['ad_type']='text';
$GLOBALS['google']['channel']='';
$GLOBALS['google']['client']='pub-0000000000000000';
$GLOBALS['google']['format']='mobile_single';
$GLOBALS['google']['https']=$_SERVER['HTTPS'];
$GLOBALS['google']['host']=$_SERVER['HTTP_HOST'];
$GLOBALS['google']['ip']=$_SERVER['REMOTE_ADDR'];
$GLOBALS['google']['markup']='xhtml';
$GLOBALS['google']['oe']='utf8';
$GLOBALS['google']['output']='xhtml';
$GLOBALS['google']['ref']=$_SERVER['HTTP_REFERER'];
$GLOBALS['google']['url']=$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$GLOBALS['google']['useragent']=$_SERVER['HTTP_USER_AGENT'];
require('http://pagead2.googlesyndication.com/pagead/show_ads.php');

?>


2. CGI/Perl

#!/usr/bin/perl

use LWP::UserAgent;
use Time::HiRes qw(gettimeofday);
use URI::Escape;

sub google_append_color {
  @color_array = split(/,/, $_[0]);
  return $color_array[$_[1] % @color_array];
}

$google_dt = sprintf("%.0f", 1000 * gettimeofday());
$google_scheme = ($ENV{"HTTPS"} eq "on") ? "https://" : "http://";
$google_host = uri_escape($google_scheme . $ENV{"HTTP_HOST"});

$google_ad_url = "http://pagead2.googlesyndication.com/pagead/ads?" .
  "ad_type=text" .
  "&channel=" .
  "&client=ca-mb-pub-0000000000000000" .
  "&dt=" . $google_dt .
  "&format=mobile_single" .
  "&host=" . $google_host .
  "&ip=" . uri_escape($ENV{"REMOTE_ADDR"}) .
  "&markup=xhtml" .
  "&oe=utf8" .
  "&output=xhtml" .
  "&ref=" . uri_escape($ENV{"HTTP_REFERER"}) .
  "&url=" . $google_host . uri_escape($ENV{"REQUEST_URI"}) .
  "&useragent=" . uri_escape($ENV{"HTTP_USER_AGENT"});

my $ua = LWP::UserAgent->new;
my $google_ad_output = $ua->get($google_ad_url);
if ($google_ad_output->is_success) {
  print $google_ad_output->content;
}


3. JSP

<%@ page import="java.io.BufferedReader,
                 java.io.InputStreamReader,
                 java.io.IOException,
                 java.io.UnsupportedEncodingException,
                 java.net.URL,
                 java.net.URLEncoder" %>
<%!

private static final String PAGEAD =
    "http://pagead2.googlesyndication.com/pagead/ads?";

private void googleAppendUrl(StringBuilder url, String param, String value)
    throws UnsupportedEncodingException {
  if (value != null) {
    String encodedValue = URLEncoder.encode(value, "UTF-8");
    url.append("&").append(param).append("=").append(encodedValue);
  }
}

private void googleAppendColor(StringBuilder url, String param,
    String value, long random) {
  String[] colorArray = value.split(",");
  url.append("&").append(param).append("=").append(
      colorArray[(int)(random % colorArray.length)]);
}

%>
<%

long googleDt = System.currentTimeMillis();
String googleHost = (request.isSecure() ? "https://" : "http://")
    + request.getHeader("Host");

StringBuilder googleAdUrlStr = new StringBuilder(PAGEAD);
googleAdUrlStr.append("ad_type=text");
googleAdUrlStr.append("&channel=");
googleAdUrlStr.append("&client=ca-mb-pub-0000000000000000");
googleAdUrlStr.append("&dt=").append(googleDt);
googleAdUrlStr.append("&format=mobile_single");
googleAppendUrl(googleAdUrlStr, "host", googleHost);
googleAppendUrl(googleAdUrlStr, "ip", request.getRemoteAddr());
googleAdUrlStr.append("&markup=xhtml");
googleAdUrlStr.append("&oe=utf8");
googleAdUrlStr.append("&output=xhtml");
googleAppendUrl(googleAdUrlStr, "ref", request.getHeader("Referer"));
String googleUrl = request.getRequestURL().toString();
if (request.getQueryString() != null) {
  googleUrl += "?" + request.getQueryString().toString();
}
googleAppendUrl(googleAdUrlStr, "url", googleUrl);
googleAppendUrl(googleAdUrlStr, "useragent", request.getHeader("User-Agent"));

try {
  URL googleAdUrl = new URL(googleAdUrlStr.toString());
  BufferedReader reader = new BufferedReader(
      new InputStreamReader(googleAdUrl.openStream(), "UTF-8"));
  for (String line; (line = reader.readLine()) != null;) {
    out.println(line);
  }
} catch (IOException e) {}

%>


4. ASP

<%

Function googleColor(value, random)
  Dim colorArray
  colorArray = Split(value, ",")
  googleColor = colorArray(random Mod (UBound(colorArray) + 1))
End Function

Dim googleTime, googleDt, googleScheme, googleHost
googleTime = DateDiff("s", "01/01/1970 00:00:00", Now())
googleDt = (1000 * googleTime) + Round(1000 * (Timer - Int(Timer)))
googleScheme = "http://"
if StrComp(Request.ServerVariables("HTTPS"), "on") = 0 Then googleScheme = "https://"
googleHost = Server.URLEncode(googleScheme & Request.ServerVariables("HTTP_HOST"))

Dim googleAdUrl, googleAdOutput
googleAdUrl = "http://pagead2.googlesyndication.com/pagead/ads?" &_
  "ad_type=text" &_
  "&channel=" &_
  "&client=ca-mb-pub-0000000000000000" &_
  "&dt=" & googleDt &_
  "&format=mobile_single" &_
  "&host=" & googleHost &_
  "&ip=" & Server.URLEncode(Request.ServerVariables("REMOTE_ADDR")) &_
  "&markup=xhtml" &_
  "&oe=utf8" &_
  "&output=xhtml" &_
  "&ref=" & Server.URLEncode(Request.ServerVariables("HTTP_REFERER")) &_
  "&url=" & googleHost & Server.URLEncode(Request.ServerVariables("URL")) &_
  "&useragent=" & Server.URLEncode(Request.ServerVariables("HTTP_USER_AGENT"))

Set googleAdOutput = Server.CreateObject("MSXML2.ServerXMLHTTP")
googleAdOutput.Open "GET", googleAdUrl, false
googleAdOutput.Send
Response.Write(googleAdOutput.responseText)

%>