<?php

/*
	Googlyzer
	Contact: Bill Edgar (bill.edgar@oaktondata.com)
	http://www.oaktondata.com/googlyzer
	
	Copyright (c) 2011-2012, Oakton Data LLC
	All rights reserved.

	Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
	    
	    * Redistributions of source code must retain the above copyright
	      notice, this list of conditions and the following disclaimer.
	    * Redistributions in binary form must reproduce the above copyright
	      notice, this list of conditions and the following disclaimer in the
	      documentation and/or other materials provided with the distribution.
	    * Neither the name of the Oakton Data LLC nor the
	      names of its contributors may be used to endorse or promote products
	      derived from this software without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
	ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
	WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
	DISCLAIMED. IN NO EVENT SHALL Oakton Data LLC BE LIABLE FOR ANY
	DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
	LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
	ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
	(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
	
	This is the googlyzer_ClientLogin PHP class file.
	
 */

if ( !class_exists( 'googlyzer_ClientLogin' ) ) {
	
	/** googlyzer_ClientLogin class
	 * 
	 * PHP class for processing Google service login using curl.
	 * @author wmsedgar
	 *
	 */
	class googlyzer_ClientLogin extends googlyzer_GoogleFeed {
		/* public variables */
		public $GA_AUTH_STATUS = 		'not_authenticated';
		public $GA_CAPTCHA_TOKEN = 		null;
		public $GA_CAPTCHA_URL = 		null;
		/* private variables */
		protected $email = 				null;
		protected $passwd = 			null;
		protected $captcha_response = 	null;
		
		/*
		* private methods
		*/
		
		/**
		*
		* private method captchaChallenge to handle Google captcha challenges during login process.
		*
		* @throws googlyzer_Exception
		*/
		private function captchaChallenge() {
			// record base URL
			$search = googlyzer_Utilities::getPatternMatch( "/Url=(https:\/\/\S+)/", $this->curl_response );
			if ( $search['found'] ) {
				$this->Url = $search['matches'][1];
			} else {
				throw new googlyzer_Exception( 'Failed to retrieve base URL in Google CAPTCHA challenge response.' );
				// failed to retrieve base URL
			}
			// record captcha URL
			$search = googlyzer_Utilities::getPatternMatch( "/CaptchaUrl=(\S+)/", $this->curl_response );
			if ( $search['found'] ) {
				$this->GA_CAPTCHA_URL = 'http://www.google.com/accounts/' . $search['matches'][1];
			} else {
				// failed to retrieve captcha URL
				throw new googlyzer_Exception( 'Failed to retrieve CAPTCHA URL in Google CAPTCHA challenge response.' );
			}
			// record captcha token
			$search = googlyzer_Utilities::getPatternMatch( "/CaptchaToken=(\S+)/", $this->curl_response );
			if ( $search['found'] ) {
				$this->GA_CAPTCHA_TOKEN = $search['matches'][1];
			} else {
				// failed to retrieve captcha token
				throw new googlyzer_Exception( 'Failed to retrieve CAPTCHA token in Google CAPTCHA challenge response.' );
			}
		}
		
		/**
		 *
		 * private method processGoogleAuthResponse to parse and record response items.
		 * 
		 * @return string
		 */
		private function processGoogleAuthResponse() {
			// first, look for auth token
			$search = googlyzer_Utilities::getPatternMatch( "/Auth=([a-z0-9_\-]+)/i", $this->curl_response );
			if ( $search['found'] ) {
				$this->GA_AUTH_TOKEN = $search['matches'][1];
				return 'authorization_successful';
				// if auth token is not found, look for Google error
			} else {
				$search = googlyzer_Utilities::getPatternMatch( "/Error=([a-z]+)/i", $this->curl_response );
				// found Google error, record and test for captcha challenge
				if ( $search['found'] ) {
					$this->google_error = $search['matches'][1];
					if ( googlyzer_Utilities::getPatternMatch( '/CaptchaRequired/', $this->google_error ) ) {
						try {
							$this->captchaChallenge();
							return 'captcha_challenge';
						} catch ( googlyzer_Exception $e ) {
							echo $e->getError();
						}
						// otherwise, it is a Google error
					} else {
						return 'error';
					}
				}
			}
		}
		
		/*
		* public methods
		*/
		
		/**
		*
		* public buildPostRequest method for constructing post request
		* 
		* @param array $args
		*/
		public function buildPostRequest( $args = array() ) {
			// must create string for $this->post_request
			// record authentication credentials for client login HTTPS POST request
			$this->post_request = "accountType=" . 
				urlencode( 'HOSTED_OR_GOOGLE' ) .
				"&Email=" . urlencode( $this->email ) .
				"&Passwd=" . urlencode( $this->passwd )
				;
			// if captcha response is being sent, include in post fields
			if ( isset( $this->captcha_response ) ) {
				$this->post_request .= "&logintoken=" . 
					urlencode( $this->GA_CAPTCHA_TOKEN ) .
					"&logincaptcha=" . 
					urlencode( $this->captcha_response )
					;
			}
			// complete construction of post fields
			$this->post_request .= "&source=" . 
				urlencode( 'googlzyer' . GOOGLYZER_VERSION ) .
				"&service=" . urlencode( 'analytics' )
				;
		}
		
		/**
		 * 
		 * public method login
		 * 
		 * @throws googlyzer_Exception
		 */
		public function login() {
			if ( $this->curl_response = curl_exec( $this->curl_obj ) ) {
				// close connection
				curl_close( $this->curl_obj );
				// no basic errors, process response
				switch ( $this->processGoogleAuthResponse() ) {
					case 'authorization_successful' :
						$this->GA_AUTH_STATUS = 'authorized';
						break;
					case 'captcha_challenge' :
						$this->GA_AUTH_STATUS = 'captcha_challenge';
						$this->captchaChallenge();
						break;
					case 'error' :
						$this->GA_AUTH_STATUS = 'google_error';
						break;
				}
			} else {
				$this->GA_AUTH_STATUS = 'curl_error';
				// record errors
				$this->getCurlError();
				// close connection
				curl_close( $this->curl_obj );
				throw new googlyzer_Exception( 'curl error' . $this->getCurlError() );
			}
		}
	} // end googlyzer_GAClientLogin class
} // end if class does not exist