<commit_before><?php

/*!
 * Detector v0.5.1
 *
 * Copyright (c) 2011-2012 <NAME>, http://dmolsen.com
 * Licensed under the MIT license
 */

// address 5.2 compatibility
if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
if (!function_exists('json_decode') || !function_exists('json_encode')) {
	require_once(__DIR__."/lib/json/jsonwrapper.php");
}

class Detector {
	
	private static $debug               = false; // gets overwritten by the config so changing this won't do anything for you...
	
	public static  $ua;
	public static  $accept;
	
	public static  $foundIn;             // this is just for the demo. won't ever really be needed i don't think
	
	private static $uaHash;
	private static $sessionID;
	private static $cookieID;
	private static $uaFeaturesMaxJS;     // all the default Modernizr Tests
	private static $uaFeaturesMinJS;     // NO default tests except media queries, meant to run those in the perrequest folder
	private static $uaFeaturesCore; 
	private static $uaFeaturesExtended;
	private static $uaFeaturesPerRequest;
	
	private static $uaDirCore;
	private static $uaDirExtended;
	
	public static $defaultFamily;
	public static $switchFamily;
	public static $noJSCookieFamilySupport;
	public static $noJSSearchFamily;
	public static $noJSDefaultFamily;
	public static $noCookieFamily;
	
	/**
	* Tests to see if:
	*     - see if this is a debug request with appropriately formed pid, else
	*     - see if a session has already been opened for the request browser, if so send the info back, else
	*     - see if the cookie has been set so we can build the profile, if so build the profile & send the info back, else
	*     - see if this browser reports being a spider, doesn't support JS or doesn't support cookies
	*     - see if detector can find an already created profile for the browser, if so send the info back, else
	*     - start the process for building a profile for this unknown browser
	*
	* Logic is based heavily on modernizr-server
	*
	* @return {Object}       an object that contains all the properties for this particular user agent
	*/
	public static function build() {
		
		// set-up the configuration options for the system
		if (!($config = @parse_ini_file(__DIR__."/config/config.ini"))) {
			// config.ini didn't exist so attempt to create it using the default file
			if (!@copy(__DIR__."/config/config.ini.default", __DIR__."/config/config.ini")) {
			    print "Please make sure config.ini.default exists before trying to have Detector build the config.ini file automagically.";
				exit;
			} else {
				$config = @parse_ini_file(__DIR__."/config/config.ini");	
			}
		}
		
		// populate some standard variables out of the config
		self::$debug                   = $config['debug'];
		
		$coreVersion                   = $config['coreVersion'];
		$extendedVersion               = $config['extendedVersion'];
		
		self::$uaFeaturesMaxJS         = $config['uaFeaturesMaxJS'];
		self::$uaFeaturesMinJS         = $config['uaFeaturesMinJS']; 
		self::$uaFeaturesCore          = $config['uaFeaturesCore']; 
		self::$uaFeaturesExtended      = $config['uaFeaturesExtended'];
		self::$uaFeaturesPerRequest    = $config['uaFeaturesPerRequest'];
		
		self::$uaDirCore               = $config['uaDirCore'];
		self::$uaDirExtended           = $config['uaDirExtended'];
		
		self::$defaultFamily           = $config['defaultFamily'];
		self::$switchFamily            = $config['switchFamily'];
		self::$noJSCookieFamilySupport = $config['noJSCookieFamilySupport'];
		self::$noJSSearchFamily        = $config['noJSSearchFamily'];
		self::$noJSDefaultFamily       = $config['noJSDefaultFamily'];
		self::$noCookieFamily          = $config['noCookieFamily'];
		
		// populate some standard variables based on the user agent string
		self::$ua                   = strip_tags($_SERVER["HTTP_USER_AGENT"]);
		self::$accept               = strip_tags($_SERVER["HTTP_ACCEPT"]);
		self::$uaHash               = md5(self::$ua);
		self::$sessionID            = md5(self::$ua."-session-".$coreVersion."-".$extendedVersion);
		self::$cookieID             = md5(self::$ua."-cookie-".$coreVersion."-".$extendedVersion);
		
		$uaFileCore                 = __DIR__."/".self::$uaDirCore."ua.".self::$uaHash.".json";
		$uaFileExtended             = __DIR__."/".self::$uaDirExtended."ua.".self::$uaHash.".json";
		
		$uaTemplateCore             = __DIR__."/".self::$uaDirCore."ua.template.json";
		$uaTemplateExtended         = __DIR__."/".self::$uaDirExtended."ua.template.json";
		
		$pid                        = (isset($_REQUEST['pid']) && preg_match("/[a-z0-9]{32}/",$_REQUEST['pid'])) ? $_REQUEST['pid'] : false;
		
		// offer the ability to review profiles saved in the system
		if ($pid && self::$debug) {
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "archive";
			
			// decode the core data
			$uaJSONCore     = json_decode(@file_get_contents(__DIR__."/".self::$uaDirCore."ua.".$pid.".json"));
			
			// find and decode the extended data
			$uaJSONExtended = json_decode(@file_get_contents(__DIR__."/".self::$uaDirExtended."ua.".$pid.".json"));
			
			// merge the data
			$mergedInfo = ($uaJSONExtended) ? (object) array_merge((array) $uaJSONCore, (array) $uaJSONExtended) : $uaJSONCore;
			
			// put the merged JSON info into session
			if (isset($_SESSION)) {
				$_SESSION[self::$sessionID] = $mergedInfo;
			}
			
			// return to the script
			return $mergedInfo;
		
		} else if (@session_start() && isset($_SESSION) && isset($_SESSION[self::$sessionID])) {
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "session";
			
			// parse the per request cookie
			$cookiePerRequest = new stdClass();
			$cookiePerRequest = self::parseCookie("pr",$cookiePerRequest);
			
			// merge the session info we already have and the info from the cookie
			$mergedInfo = (isset($cookiePerRequest)) ? (object) array_merge((array) $_SESSION[self::$sessionID], (array) $cookiePerRequest) : $_SESSION[self::$sessionID];
			
			// save the new info to the session
			$_SESSION[self::$sessionID] = $mergedInfo;

			// send the data back to the script to be used
			return $mergedInfo;
			
		} else if (isset($_COOKIE) && isset($_COOKIE[self::$cookieID])) {
			
			// to be clear, this section means that a UA was unknown, was profiled with modernizr & now we're saving that data to build a new profile
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "cookie";
			
			// open the JSON template core & extended files that will be populated
			$jsonTemplateCore     = self::openUAFile($uaTemplateCore);
			$jsonTemplateExtended = self::openUAFile($uaTemplateExtended);
			
			// use ua-parser-php to set-up the basic properties for this UA, populate other core properties
			$jsonTemplateCore->ua          = self::$ua;
			$jsonTemplateCore->uaHash      = self::$uaHash;
			$jsonTemplateCore->coreVersion = $coreVersion;
			$jsonTemplateCore              = self::createUAProperties($jsonTemplateCore);
			
			// populate extended properties
			$jsonTemplateExtended                  = !isset($jsonTemplateExtended) ? new stdClass() : $jsonTemplateExtended;
			$jsonTemplateExtended->ua              = self::$ua;
			$jsonTemplateExtended->uaHash          = self::$uaHash;
			$jsonTemplateExtended->extendedVersion = $extendedVersion;
			
			// create an object to hold any of the per request data. it shouldn't be saved to file but it should be added to the session
			$cookiePerRequest = new stdClass();
			
			// push features into the same level as the general device information
			// change 1/0 to true/false. why? 'cause that's what i like to read ;)
			$jsonTemplateCore     = self::parseCookie("core",$jsonTemplateCore,true);
			$jsonTemplateExtended = self::parseCookie("extended",$jsonTemplateExtended,true);
			$cookiePerRequest     = self::parseCookie("pr",$cookiePerRequest,true);

			// merge the data for future requests
			$mergedInfo = new stdClass();
			$mergedInfo = ($jsonTemplateExtended) ? (object) array_merge((array) $jsonTemplateCore, (array) $jsonTemplateExtended) : $jsonTemplateCore;
			$mergedInfo = ($cookiePerRequest) ? (object) array_merge((array) $mergedInfo, (array) $cookiePerRequest) : $mergedInfo;

			// write out to disk for future requests that might have the same UA<commit_msg>cleaning up extra whitespace<commit_after><?php

/*!
 * Detector v0.5.1
 *
 * Copyright (c) 2011-2012 <NAME>, http://dmolsen.com
 * Licensed under the MIT license
 */

// address 5.2 compatibility
if (!defined('__DIR__')) define('__DIR__', dirname(__FILE__));
if (!function_exists('json_decode') || !function_exists('json_encode')) {
	require_once(__DIR__."/lib/json/jsonwrapper.php");
}

class Detector {
	
	private static $debug               = false; // gets overwritten by the config so changing this won't do anything for you...
	
	public static  $ua;
	public static  $accept;
	
	public static  $foundIn;             // this is just for the demo. won't ever really be needed i don't think
	
	private static $uaHash;
	private static $sessionID;
	private static $cookieID;
	private static $uaFeaturesMaxJS;     // all the default Modernizr Tests
	private static $uaFeaturesMinJS;     // NO default tests except media queries, meant to run those in the perrequest folder
	private static $uaFeaturesCore; 
	private static $uaFeaturesExtended;
	private static $uaFeaturesPerRequest;
	
	private static $uaDirCore;
	private static $uaDirExtended;
	
	public static $defaultFamily;
	public static $switchFamily;
	public static $noJSCookieFamilySupport;
	public static $noJSSearchFamily;
	public static $noJSDefaultFamily;
	public static $noCookieFamily;
	
	/**
	* Tests to see if:
	*     - see if this is a debug request with appropriately formed pid, else
	*     - see if a session has already been opened for the request browser, if so send the info back, else
	*     - see if the cookie has been set so we can build the profile, if so build the profile & send the info back, else
	*     - see if this browser reports being a spider, doesn't support JS or doesn't support cookies
	*     - see if detector can find an already created profile for the browser, if so send the info back, else
	*     - start the process for building a profile for this unknown browser
	*
	* Logic is based heavily on modernizr-server
	*
	* @return {Object}       an object that contains all the properties for this particular user agent
	*/
	public static function build() {
		
		// set-up the configuration options for the system
		if (!($config = @parse_ini_file(__DIR__."/config/config.ini"))) {
			// config.ini didn't exist so attempt to create it using the default file
			if (!@copy(__DIR__."/config/config.ini.default", __DIR__."/config/config.ini")) {
			    print "Please make sure config.ini.default exists before trying to have Detector build the config.ini file automagically.";
				exit;
			} else {
				$config = @parse_ini_file(__DIR__."/config/config.ini");	
			}
		}
		
		// populate some standard variables out of the config
		self::$debug                   = $config['debug'];
		
		$coreVersion                   = $config['coreVersion'];
		$extendedVersion               = $config['extendedVersion'];
		
		self::$uaFeaturesMaxJS         = $config['uaFeaturesMaxJS'];
		self::$uaFeaturesMinJS         = $config['uaFeaturesMinJS']; 
		self::$uaFeaturesCore          = $config['uaFeaturesCore']; 
		self::$uaFeaturesExtended      = $config['uaFeaturesExtended'];
		self::$uaFeaturesPerRequest    = $config['uaFeaturesPerRequest'];
		
		self::$uaDirCore               = $config['uaDirCore'];
		self::$uaDirExtended           = $config['uaDirExtended'];
		
		self::$defaultFamily           = $config['defaultFamily'];
		self::$switchFamily            = $config['switchFamily'];
		self::$noJSCookieFamilySupport = $config['noJSCookieFamilySupport'];
		self::$noJSSearchFamily        = $config['noJSSearchFamily'];
		self::$noJSDefaultFamily       = $config['noJSDefaultFamily'];
		self::$noCookieFamily          = $config['noCookieFamily'];
		
		// populate some standard variables based on the user agent string
		self::$ua                   = strip_tags($_SERVER["HTTP_USER_AGENT"]);
		self::$accept               = strip_tags($_SERVER["HTTP_ACCEPT"]);
		self::$uaHash               = md5(self::$ua);
		self::$sessionID            = md5(self::$ua."-session-".$coreVersion."-".$extendedVersion);
		self::$cookieID             = md5(self::$ua."-cookie-".$coreVersion."-".$extendedVersion);
		
		$uaFileCore                 = __DIR__."/".self::$uaDirCore."ua.".self::$uaHash.".json";
		$uaFileExtended             = __DIR__."/".self::$uaDirExtended."ua.".self::$uaHash.".json";
		
		$uaTemplateCore             = __DIR__."/".self::$uaDirCore."ua.template.json";
		$uaTemplateExtended         = __DIR__."/".self::$uaDirExtended."ua.template.json";
		
		$pid                        = (isset($_REQUEST['pid']) && preg_match("/[a-z0-9]{32}/",$_REQUEST['pid'])) ? $_REQUEST['pid'] : false;
		
		// offer the ability to review profiles saved in the system
		if ($pid && self::$debug) {
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "archive";
			
			// decode the core data
			$uaJSONCore     = json_decode(@file_get_contents(__DIR__."/".self::$uaDirCore."ua.".$pid.".json"));
			
			// find and decode the extended data
			$uaJSONExtended = json_decode(@file_get_contents(__DIR__."/".self::$uaDirExtended."ua.".$pid.".json"));
			
			// merge the data
			$mergedInfo = ($uaJSONExtended) ? (object) array_merge((array) $uaJSONCore, (array) $uaJSONExtended) : $uaJSONCore;
			
			// put the merged JSON info into session
			if (isset($_SESSION)) {
				$_SESSION[self::$sessionID] = $mergedInfo;
			}
			
			// return to the script
			return $mergedInfo;
		
		} else if (@session_start() && isset($_SESSION) && isset($_SESSION[self::$sessionID])) {
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "session";
			
			// parse the per request cookie
			$cookiePerRequest = new stdClass();
			$cookiePerRequest = self::parseCookie("pr",$cookiePerRequest);
			
			// merge the session info we already have and the info from the cookie
			$mergedInfo = (isset($cookiePerRequest)) ? (object) array_merge((array) $_SESSION[self::$sessionID], (array) $cookiePerRequest) : $_SESSION[self::$sessionID];
			
			// save the new info to the session
			$_SESSION[self::$sessionID] = $mergedInfo;

			// send the data back to the script to be used
			return $mergedInfo;
			
		} else if (isset($_COOKIE) && isset($_COOKIE[self::$cookieID])) {
			
			// to be clear, this section means that a UA was unknown, was profiled with modernizr & now we're saving that data to build a new profile
			
			// where did we find this info to display... probably only need this for the demo
			self::$foundIn = "cookie";
			
			// open the JSON template core & extended files that will be populated
			$jsonTemplateCore     = self::openUAFile($uaTemplateCore);
			$jsonTemplateExtended = self::openUAFile($uaTemplateExtended);
			
			// use ua-parser-php to set-up the basic properties for this UA, populate other core properties
			$jsonTemplateCore->ua          = self::$ua;
			$jsonTemplateCore->uaHash      = self::$uaHash;
			$jsonTemplateCore->coreVersion = $coreVersion;
			$jsonTemplateCore              = self::createUAProperties($jsonTemplateCore);
			
			// populate extended properties
			$jsonTemplateExtended                  = !isset($jsonTemplateExtended) ? new stdClass() : $jsonTemplateExtended;
			$jsonTemplateExtended->ua              = self::$ua;
			$jsonTemplateExtended->uaHash          = self::$uaHash;
			$jsonTemplateExtended->extendedVersion = $extendedVersion;
			
			// create an object to hold any of the per request data. it shouldn't be saved to file but it should be added to the session
			$cookiePerRequest = new stdClass();
			
			// push features into the same level as the general device information
			// change 1/0 to true/false. why? 'cause that's what i like to read ;)
			$jsonTemplateCore     = self::parseCookie("core",$jsonTemplateCore,true);
			$jsonTemplateExtended = self::parseCookie("extended",$jsonTemplateExtended,true);
			$cookiePerRequest     = self::parseCookie("pr",$cookiePerRequest,true);

			// merge the data for future requests
			$mergedInfo = new stdClass();
			$mergedInfo = ($jsonTemplateExtended) ? (object) array_merge((array) $jsonTemplateCore, (array) $jsonTemplateExtended) : $jsonTemplateCore;
			$mergedInfo = ($cookiePerRequest) ? (object) array_merge((array) $mergedInfo, (array) $cookiePerRequest) : $mergedInfo;
			
			// write out to disk for future requests that might have the same UA
{'fraction_non_alphanumeric': 0.12461465496798672, 'fraction_numerical': 0.002608489447474508, 'mean_word_length': 3.3600413543551304, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4521160', 'n_tokens_mistral': 5315, 'n_tokens_neox': 4726, 'n_words': 1434}