Experiment.php 19.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
<?php

/**
 * Server-Side Google Analytics Content Experiments PHP Client
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License (LGPL) as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
 *
 * Google Analytics is a registered trademark of Google Inc.
 *
 * @link      https://github.com/thomasbachem/php-gacx
 *
 * @license   http://www.gnu.org/licenses/lgpl.html
 * @author    Thomas Bachem <mail@thomasbachem.com>
 */

namespace UnitedPrototype\GoogleAnalytics;

use Exception;
use UnexpectedValueException;

/**
 * @link https://developers.google.com/analytics/devguides/collection/gajs/experiments
 */
class Experiment {

    const GACX_URL = 'http://www.google-analytics.com/cx/api.js';

    /**
     * @var string
     */
    protected $id;

    /**
     * @var array
     */
    protected $data;

    /**
     * The connection timeout for cURL.
     *
     * @var int
     */
    protected static $connectTimeout = self::DEFAULT_CONNECT_TIMEOUT;

    /**
     * The request timeout for cURL.
     *
     * @var int
     */
    protected static $timeout = self::DEFAULT_TIMEOUT;

    /**
     * The domain name that is also used by Google Analytics.
     * Defaults to $_SERVER['HTTP_HOST'] if defined.
     *
     * @var string
     */
    protected static $domainName = self::DEFAULT_DOMAIN_NAME;

    /**
     * The cookie path that is also used by Google Analytics.
     * Defaults to "/".
     *
     * @var string
     */
    protected static $cookiePath = self::DEFAULT_COOKIE_PATH;

    /**
     * The cookie expiration time in seconds.
     *
     * @var int
     */
    protected static $cookieExpirationSeconds = self::DEFAULT_COOKIE_EXPIRATION_SECONDS;

    /**
     * Optional. A cache directory that will be used to cache
     * the requests being made to the Google Analytics servers.
     *
     * @var string
     */
    protected static $cacheDir;

    /**
     * Cache lifetime in seconds. Defines how often new variation
     * weights will be retrieved from the Google Analytics servers
     * if caching is used.
     *
     * @var int
     */
    protected static $cacheTtl = self::DEFAULT_CACHE_TTL;

    /**
     * Whether to use file locking for the cache.
     *
     * @var bool
     */
    protected static $cacheLocking = self::DEFAULT_CACHE_LOCKING;

    const ORIGINAL_VARIATION = 0;
    const NO_CHOSEN_VARIATION = -1;
    const NOT_PARTICIPATING = -2;
    const DEFAULT_CONNECT_TIMEOUT = 2;
    const DEFAULT_TIMEOUT = 2;
    const DEFAULT_DOMAIN_NAME = 'auto';
    const DEFAULT_COOKIE_PATH = '/';
    const DEFAULT_COOKIE_EXPIRATION_SECONDS = 48211200;
    const DEFAULT_CACHE_TTL = 60;
    const DEFAULT_CACHE_LOCKING = true;

    /**
     * @param string $id
     */
    public function __construct($id) {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function getId() {
        return $this->id;
    }

    /**
     * @param int $connectTimeout
     */
    public static function setConnectTimeout($connectTimeout) {
        static::$connectTimeout = (int) $connectTimeout;
    }

    /**
     * @return int
     */
    public static function getConnectTimeout() {
        return static::$connectTimeout;
    }

    /**
     * @param int $timeout
     */
    public static function setTimeout($timeout) {
        static::$timeout = (int) $timeout;
    }

    /**
     * @return int
     */
    public static function getTimeout() {
        return static::$timeout;
    }

    /**
     * @param string $domainName
     */
    public static function setDomainName($domainName) {
        static::$domainName = strtolower($domainName);
    }

    /**
     * @return string
     */
    public static function getDomainName() {
        if (static::$domainName == 'auto') {
            return isset($_SERVER['HTTP_HOST']) ? strtolower($_SERVER['HTTP_HOST']) : null;
        } elseif (static::$domainName) {
            return static::$domainName;
        } else {
            throw new UnexpectedValueException('Unable to determine domain name, please provide one via setDomainName()!');
        }
    }

    /**
     * @param string $cookiePath
     */
    public static function setCookiePath($cookiePath) {
        static::$cookiePath = $cookiePath;
    }

    /**
     * @return string
     */
    public static function getCookiePath() {
        return static::$cookiePath;
    }

    /**
     * @param int $cookieExpirationSeconds
     */
    public static function setCookieExpirationSeconds($cookieExpirationSeconds) {
        static::$cookieExpirationSeconds = (int) $cookieExpirationSeconds;
    }

    /**
     * @return int
     */
    public static function getCookieExpirationSeconds() {
        return static::$cookieExpirationSeconds;
    }

    /**
     * @param string $cacheDir
     */
    public static function setCacheDir($cacheDir) {
        static::$cacheDir = rtrim($cacheDir, DIRECTORY_SEPARATOR);
    }

    /**
     * @return string
     */
    public static function getCacheDir() {
        return static::$cacheDir;
    }

    /**
     * @param int $cacheTtl
     */
    public static function setCacheTtl($cacheTtl) {
        self::$cacheTtl = (int) $cacheTtl;
    }

    /**
     * @return int
     */
    public static function getCacheTtl() {
        return self::$cacheTtl;
    }

    /**
     * @param bool $cacheLocking
     */
    public static function setCacheLocking($cacheLocking) {
        static::$cacheLocking = (bool) $cacheLocking;
    }

    /**
     * @return bool
     */
    public static function getCacheLocking() {
        return static::$cacheLocking;
    }

    /**
     * @return array
     */
    protected function getData() {
        if ($this->data === null) {
            $this->data = $this->loadData();
        }
        return $this->data;
    }

    /**
     * Retrieves the experiment data from Google Analytics servers. This allows
     * us to take the different variation weights into account to make use of
     * the multi-armed bandit algorithm (https://support.google.com/analytics/answer/2844870).
     *
     * @return array
     */
    protected function loadData() {
        $response = null;
        $cacheDir = static::getCacheDir();

        if ($cacheDir) {
            $cachePath = $cacheDir . DIRECTORY_SEPARATOR . 'gacx-' . rawurlencode($this->id) . '.cache';
            if (is_readable($cachePath) && time() <= filemtime($cachePath) + static::getCacheTtl()) {
                $fp = fopen($cachePath, 'r');
                if (static::getCacheLocking()) {
                    // Wait for another process that acquired an exclusive lock (see below)
                    // because it is going to write new contents to the cache file
                    flock($fp, LOCK_SH);
                }
                $response = stream_get_contents($fp);
                flock($fp, LOCK_UN);
                fclose($fp);
            }
        }

        if (!$response) {
            if (!extension_loaded('curl')) {
                throw new Exception('php-gacx requires the cURL extension to be installed.');
            }

            if ($cacheDir) {
                @mkdir($cacheDir, 0777, true);

                // Lock the cache file so we won't do multiple requests in parallel
                $fp = fopen($cachePath, 'c');
                if (static::getCacheLocking()) {
                    flock($fp, LOCK_EX);
                }
            }

            // We use this JS API trick instead of the official Google Analytics
            // management API as does only work with OAuth
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, static::getConnectTimeout());
            curl_setopt($curl, CURLOPT_TIMEOUT, static::getTimeout());
            curl_setopt($curl, CURLOPT_FAILONERROR, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_VERBOSE, false);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_USERAGENT, '');
            curl_setopt($curl, CURLOPT_URL, self::GACX_URL . '?experiment=' . rawurlencode($this->id));
            $response = curl_exec($curl);
            $error = curl_error($curl);
            curl_close($curl);

            if ($cacheDir && $response) {
                if (!is_writable($cacheDir)) {
                    throw new Exception('Cache directory "' . $cacheDir . '" is not writable.');
                }

                ftruncate($fp, 0);
                fwrite($fp, $response);
                fflush($fp);
            }

            if ($cacheDir) {
                flock($fp, LOCK_UN);
                fclose($fp);
            }
        }

        if (!$response) {
            throw new Exception('Unable to retrieve Google Analytics Content Experiments API response: ' . (isset($error) ? $error : '') . (strlen($response) ? "\n" . $response : ''));
        } else {
            // Use a recursive regex to match nested JSON objects
            // (relies on the fact that strings do not contain "{" or "}"!)
            if (!preg_match('#\.experiments_\s*=\s*(\{(?:[^{}]+|(?1))+\})#', $response, $m)) {
                throw new UnexpectedValueException('Unable to find experiments in Google Analytics Content Experiments API response.');
            } else {
                $experiments = json_decode($m[1], true);
                if ($experiments === null) {
                    throw new UnexpectedValueException('Unable to parse JSON from Google Analytics Content Experiments API response.');
                } else {
                    if (isset($experiments[$this->id]['data'])) {
                        return $experiments[$this->id]['data'];
                    } elseif (isset($experiments[$this->id]['error'])) {
                        throw new UnexpectedValueException('Error from Google Analytics Content Experiments API: ' . $experiments[$this->id]['error']['code'] . ' - ' . $experiments[$this->id]['error']['message']);
                    } else {
                        throw new UnexpectedValueException('Unable to find experiment data in JSON from Google Analytics Content Experiments API response.');
                    }
                }
            }
        }
    }

    /**
     * Works just like cxApi.chooseVariation()
     *
     * @link https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs-methods
     *
     * @param  string  $utmx        Value of the "__utmx" cookie. Defaults to $_COOKIE['__utmx'] if defined
     * @param  string  $utmxx       Value of the "__utmxx" cookie. Defaults to $_COOKIE['__utmxx'] if defined
     * @param  bool    $setCookies  See setChosenVariation() - sets the "__utmx" and "__utmxx" cookies with
     *                              setrawcookie() if true
     * @return int
     */
    public function chooseVariation($utmx = null, $utmxx = null, $setCookies = true) {
        $variation = $this->getChosenVariation($utmx);

        if ($variation === null) {
            $variation = $this->chooseNewVariation();
            $this->setChosenVariation($variation, $utmx, $utmxx, $setCookies);
        }

        return $variation;
    }

    /**
     * @return int
     */
    public function chooseNewVariation() {
        $data = $this->getData();

        // Extracted from Google Analytics Content Experiments JS client
        $rand = mt_rand(0, 1E9) / 1E9;
        foreach ($data['items'] as $item) {
            if (isset($item['weight']) && empty($item['disabled'])) {
                // Disabled variations have a weight of 0, so they will never match here
                if ($rand < $item['weight']) {
                    if ($item['id'] !== null) {
                        return (int) $item['id'];
                    } else {
                        return self::NOT_PARTICIPATING;
                    }
                }
                $rand -= $item['weight'];
            }
        }

        return self::ORIGINAL_VARIATION;
    }

    /**
     * Works just like cxApi.getChosenVariation()
     *
     * @link https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs-methods
     *
     * @param  string  $utmx  Value of the "__utmx" cookie. Defaults to $_COOKIE['__utmx'] if defined
     * @return int|null
     */
    public function getChosenVariation($utmx = null) {
        if ($utmx === null && isset($_COOKIE['__utmx'])) {
            $utmx = $_COOKIE['__utmx'];
        }

        // Example format of the "__utmx" cookie value:
        // 159991919.ft-5xaLPSturFXCPgoFrKg$0:1.ft-6uzLPSelrFQsPgouIkD$0:2
        // [DOMAIN_HASH].[EXPERIMENT_ID]$0:[VARIATION].[EXPERIMENT_ID]$0:[VARIATION]
        $experiments = explode('.', $utmx);
        if (count($experiments) > 1) {
            // Strip domain hash
            array_shift($experiments);

            foreach ($experiments as $experiment) {
                if (preg_match('/^([^$]+)\$([^:]+):(.*)$/', $experiment, $m)) {
                    if ($m[1] == $this->id) {
                        // It seems like there can be stored multiple variations here,
                        // but that it is deprecated
                        $variations = explode('-', $m[3]);
                        return (int) $variations[0];
                    }
                }
            }
        }

        return null;
    }

    /**
     * Works just like cxApi.setChosenVariation()
     *
     * @link https://developers.google.com/analytics/devguides/collection/gajs/experiments#cxjs-methods
     *
     * @param  int     $variation   Variation number
     * @param  string  $utmx        Value of the "__utmx" cookie. Defaults to $_COOKIE['__utmx'] if defined
     * @param  string  $utmxx       Value of the "__utmxx" cookie. Defaults to $_COOKIE['__utmxx'] if defined
     * @param  bool    $setCookies  Sets the "__utmx" and "__utmxx" cookies with setrawcookie() if true
     * @return array                Returns an array of cookies to set so you can set the cookies thru your
     *                              framework's methods if you set $setCookies to false.
     */
    public function setChosenVariation($variation, $utmx = null, $utmxx = null, $setCookies = true) {
        if ($utmx === null && isset($_COOKIE['__utmx'])) {
            $utmx = $_COOKIE['__utmx'];
        }
        if ($utmxx === null && isset($_COOKIE['__utmxx'])) {
            $utmxx = $_COOKIE['__utmxx'];
        }

        $domainName = static::getDomainName();
        $domainHash = static::generateHash($domainName);

        $cookies = array(
            '__utmx' => array(
                'value' => $utmx,
                'expire' => time() + static::getCookieExpirationSeconds(),
                'path' => static::getCookiePath(),
                'domain' => '.' . $domainName,
                'secure' => false,
                'httponly' => false,
            ),
            '__utmxx' => array(
                'value' => $utmxx,
                'expire' => time() + static::getCookieExpirationSeconds(),
                'path' => static::getCookiePath(),
                'domain' => '.' . $domainName,
                'secure' => false,
                'httponly' => false,
            ),
        );

        // Example format of the "__utmx" cookie value:
        // 159991919.ft-5xaLPSturFXCPgoFrKg$0:1.ft-6uzLPSelrFQsPgouIkD$0:2
        // [DOMAIN_HASH].[EXPERIMENT_ID]$0:[VARIATION].[EXPERIMENT_ID]$0:[VARIATION]
        $experiments = explode('.', $utmx);
        if (count($experiments) > 1) {
            // Modify "__utmx" cookie value
            $domainHash = array_shift($experiments);
            $found = false;
            foreach ($experiments as &$experiment) {
                if (preg_match('/^([^$]+)\$([^:]+):(.*)$/', $experiment, $m)) {
                    if ($m[1] == $this->id) {
                        $found = true;
                        $experiment = $m[1] . '$' . $m[2] . ':' . $variation;
                    }
                }
            }
            if (!$found) {
                $experiments[] = $this->id . '$0' . ':' . $variation;
            }
            $cookies['__utmx']['value'] = $domainHash . '.' . implode('.', $experiments);
        } else {
            // Create new "__utmx" cookie value
            $cookies['__utmx']['value'] = $domainHash . '.' . $this->id . '$0' . ':' . $variation;
        }

        // Example format of the "__utmxx" cookie value:
        // 159991919.ft-5xaLPSturFXCPgoFrKg$0:1380888455:8035200.ft-6uzLPSelrFQsPgouIkD$0:1380888456:8035200
        // [DOMAIN_HASH].[EXPERIMENT_ID]$0:[TIMESTAMP]:8035200.[EXPERIMENT_ID]$0:[TIMESTAMP]:8035200
        $experiments = explode('.', $utmxx);
        if (count($experiments) > 1) {
            // Modify "__utmxx" cookie value
            $domainHash = array_shift($experiments);
            $found = false;
            foreach ($experiments as &$experiment) {
                // There is an optional part at the very end of the cookie value
                // which seems not to be used as of now
                if (preg_match('/^([^$]+)\$([^:]+):([^:]+):([^:]+):?(.*)$/', $experiment, $m)) {
                    if ($m[1] == $this->id) {
                        $found = true;
                        $experiment = $m[1] . '$' . $m[2] . ':' . time() . ':' . $m[4] . ($m[5] ? ':' . $m[5] : '');
                    }
                }
            }
            if (!$found) {
                $experiments[] = $this->id . '$0' . ':' . time() . ':' . 8035200;
            }
            $cookies['__utmxx']['value'] = $domainHash . '.' . implode('.', $experiments);
        } else {
            // Create new "__utmxx" cookie value
            // (the "8035200" value is hardcoded in the GACX JS client)
            $cookies['__utmxx']['value'] = $domainHash . '.' . $this->id . '$0' . ':' . time() . ':' . 8035200;
        }

        if ($setCookies) {
            foreach ($cookies as $name => $cookie) {
                setrawcookie($name, $cookie['value'], $cookie['expire'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']);
            }
        }

        return $cookies;
    }

    /**
     * Generates a valid Google Analytics hash for the input string.
     * All Google Analytics cookie values begin with a hash of the domain name.
     *
     * @link http://code.google.com/p/gaforflash/source/browse/trunk/src/com/google/analytics/core/Utils.as#44
     *
     * @param  string $string
     * @return int
     */
    protected static function generateHash($string) {
        $string = (string) $string;
        $hash = 1;

        if ($string !== null && $string !== '') {
            $hash = 0;

            $length = strlen($string);
            for ($pos = $length - 1; $pos >= 0; $pos--) {
                $current = ord($string[$pos]);
                $hash = (($hash << 6) & 0xfffffff) + $current + ($current << 14);
                $leftMost7 = $hash & 0xfe00000;
                if ($leftMost7 != 0) {
                    $hash ^= $leftMost7 >> 21;
                }
            }
        }

        return $hash;
    }

}

?>