<?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_GoogleFeed PHP class file.
	
 */

if ( !class_exists( 'googlyzer_GoogleFeed' ) ) {

	/** googlyzer_GoogleFeed class
	 *
	 * PHP base class for creating a Google feed using curl.
	 * @author wmsedgar
	 *
	 */
	abstract class googlyzer_GoogleFeed {
		/* public variables */
		public $GA_AUTH_TOKEN = 		null;
		public $REQ_STATUS = 			null;
		/* private variables */
		protected $curl_error = 		array(
			'message' =>				null,
			'number' =>					null,
			'info' =>					null
			);
		protected $curl_obj = 			null;
		protected $curl_response = 		null;
		protected $feedArgs = 			array();
		protected $feedType = 			null;
		protected $feed_url =			null;
		protected $google_error = 		null;
		protected $headers = 			array();
		protected $post_request = 		null;
		protected $request_status = 	array(
			'info' =>					null,
			'type' =>					null
			);
		
		/**
		 * old style constructor method for backward PHP compatibility
		 */ 
		public function googlyzer_GoogleFeed( $feedType, $url, $method, $feedSpecificSettings = array() ) {
			$this->__construct( $feedType, $url, $method, $feedSpecificSettings );
		}
		
		/**
		 * public constructor method
		 */
		public function __construct( $feedType, $url, $method, $feedSpecificSettings = array() ) {
			$this->feedType = $feedType;
			// set feed specific settings, if appropriate
			if ( !empty( $feedSpecificSettings ) ) {
				$this->setProperties( $feedSpecificSettings );
			}
			// if we're not dealing with a login, check for Google auth token
			if ( $this->feedType !== 'login' ) {
				// make sure an auth token has been passed, or raise exception
				if ( isset( $this->GA_AUTH_TOKEN ) ) {
					$this->headers = array(
					    "Authorization: GoogleLogin Auth=" . $this->GA_AUTH_TOKEN
						);
				} else {
					throw new googlyzer_Exception( 'Missing authentication token. Unable to create Google feed.' );
				}
			}
			// make sure url has been passed, or cannot create feed
			if ( isset( $url ) ) {
				if ( $feedType === 'data_request' ) {
					$this->buildPostRequest( $feedSpecificSettings['feedArgs'] );
					$this->feed_url = $url . $this->post_request;
				} else {
					$this->feed_url = $url;
				}
			} else {
				throw new googlyzer_Exception( 'Missing url for creation of Google data feed request.' );
			}
			// set up curl object
			$this->curlSetup();
			// make sure request method has been set, or raise exception
			if ( isset( $method ) ) {
				$this->$method( $this->feedArgs );
			} else {
				throw new googlyzer_Exception( 'Missing GET or POST parameter for creation of Google data feed request.' );
			}
		}
		
		/*
		 * private methods
		 */
		
		/**
		*
		* method for initializing GET specific settings
		*/
		private function GET( $args = array() ) {
			curl_setopt( $this->curl_obj, CURLOPT_HTTPHEADER, $this->headers);
		}
		
		private function POST( $args = array() ) {
			$this->buildPostRequest( $args );
			curl_setopt( $this->curl_obj, CURLOPT_HEADER, true );
			curl_setopt( $this->curl_obj, CURLOPT_POST, true );
			curl_setopt( $this->curl_obj, CURLOPT_POSTFIELDS, $this->post_request );
			curl_setopt( $this->curl_obj, CURLOPT_HTTPAUTH, CURLAUTH_ANY );
			curl_setopt( $this->curl_obj, CURLOPT_SSL_VERIFYPEER, false );
		}
		
		/**
		 * 
		 * protected curlSetup method to set curl object connection options
		 */
		protected function curlSetup() {
			// initialize curl object
			$this->curl_obj = curl_init( $this->feed_url );
			// required for both GET and POST
			curl_setopt( $this->curl_obj, CURLOPT_RETURNTRANSFER, true );
			// debugging settings
			// curl_setopt( $this->curl_obj, CURLINFO_HEADER_OUT, true ); // for debugging the request
			
		}
		
		/**
		 * 
		 * protected setCurlError method
		 */
		protected function setCurlError() {
			$this->curl_error['message'] = curl_error( $this->curl_obj );
			$this->curl_error['number'] = curl_errno( $this->curl_obj );
		}
		
		/*
		 * public methods
		 */
		
		/**
		*
		* method for constructing post request (must be overridden)
		*/
		public function buildPostRequest( $args = array() ) {
			// must create string for $this->post_request
		}
		
		/**
		 * 
		 * public getCurlError method
		 * @return string
		 */
		public function getCurlError() {
			return $this->curl_error['number'] . " " . $this->curl_error['message'];
		}
		
		/**
		 * 
		 * public getGoogleError method
		 */
		public function getGoogleError() {
			return $this->google_error;
		}
		
		/**
		 * 
		 * public getFeed method to retrieve feed from Google Analytics
		 * 
		 * @throws googlyzer_Exception
		 */
		public function getFeed() {
			// open connection and get response
			if ( $this->curl_response = curl_exec( $this->curl_obj ) ) {
				// debugging setting
				// var_dump( curl_getinfo($this->curl_obj, CURLINFO_HEADER_OUT ) ); // for debugging the request
				$this->REQ_STATUS = 'success';
				$status = googlyzer_Utilities::getCurlInfo( $this->curl_obj );
				// check curl return info for failure codes
				if ( $status['info']['http_code'] != 200 ) {
					$this->REQ_STATUS = 'failure';
					$this->google_error = "Google Error. HTTP response code " . $status['info']['http_code'] . " " . $status['type'];
					// close connection
					curl_close( $this->curl_obj );
					throw new googlyzer_Exception( '<br />' . $this->getGoogleError() . '<br />Data feed request: ' . $this->post_request );
				}
				// close connection
				curl_close( $this->curl_obj );
			// curl connection failure
			} else {
				$this->REQ_STATUS = 'curl_error';
				// record errors
				$this->setCurlError();
				// close connection
				curl_close( $this->curl_obj );
				throw new googlyzer_Exception( $this->getCurlError() );
			}
		}
		
		/**
		 * 
		 * method for handling data feed (must be overridden)
		 */
		public function handleFeed() {
			// handle feed
		}
		
		/**
		 * 
		 * public method setProperties to set object attributes using associative array.
		 * 
		 * @param array $properties
		 */
		public function setProperties( $properties ) {
			foreach ( $properties as $key => $value ) {
				$this->$key = $value;
			}
		}
	}
}
?>