<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/common/webaccount/webaccount.class.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(dirname(__FILE__).'/../webaccount/sushee_oauth.class.php');
require_once(dirname(__FILE__).'/../nectil_element.class.php');


class Sushee_WebAPI extends Sushee_Element{
	function Sushee_WebAPI($values){
		$moduleInfo = moduleInfo('webapi');
		parent::sushee_Element($moduleInfo->ID,$values);
	}
}

class Sushee_WebAccount extends sushee_Element{
	
	var $service = false;
	
	function Sushee_WebAccount($values){
		$moduleInfo = moduleInfo('webaccount');
		parent::sushee_Element($moduleInfo->ID,$values);
	}
	
	function authorize(){
		// edition : will redirect to the service authorization page if in edition state (--> passing to requested state)
		// registered : will ask for permanent token if in registered state (-->passing to authorized state)
		// will skip if already authorized
		
		// account properties 
		$this->loadFields();
		$current_state = $this->getField('Authorization_State');
		$service = $this->getWebAPI();
		
		// already authorized
		if($current_state == 'authorized'){
			;
		}else if($current_state == 'requested' && $_GET['oauth_token']){
			$this->setField('Authorization_State','registered');
			$connection = new Sushee_Oauth($service->getField('Consumer_Key'), $service->getField('Consumer_Secret'),$this->getField('OAuth_Token'),$this->getField('OAuth_Token_Secret'));
			$access_token = $connection->getAccessToken($service->getField('Access_Token_URL'),$_REQUEST['oauth_verifier']);
			
			if(200 == $connection->http_code){
				// saving permanent access tokens in database webaccount
				$this->setField('OAuth_Token',$access_token["oauth_token"]);
			    $this->setField('OAuth_Token_Secret',$access_token["oauth_token_secret"]);
			    $this->setField('Authorization_State','authorized');
				$this->update();
			}else{
				$this->setError('could not get permanent access tokens');
				return false;
			}
		}else{
			// not authenticated yet, getting the initializing tokens and redirecting to the Twitter authentication page
			$connection = new Sushee_Oauth($service->getField('Consumer_Key'), $service->getField('Consumer_Secret'));
			$request_token = $connection->getRequestToken($service->getField('Request_Token_URL'),$GLOBALS['SusheeProtocol'].$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
			$this->setField('OAuth_Token',$request_token["oauth_token"]);
		    $this->setField('OAuth_Token_Secret',$request_token["oauth_token_secret"]);
			$this->setField('Authorization_State','requested');
			$this->update();
			redirect($service->getField('Authorize_URL').'?oauth_token='.$request_token["oauth_token"]);
		}
		
		return true;
	}
	
	function getWebAPI(){
		if(!$this->service){
			$this->loadFields();
			$serviceType = $this->getField('API');

			// service properties
			$db_conn = db_connect();
			$serviceModuleInfo = moduleInfo('webapi');
			$service_sql = 'SELECT * FROM `'.$serviceModuleInfo->getTableName().'` WHERE `Denomination` = "'.encode_for_db($serviceType).'" AND `Activity` = 1;';
			sql_log($service_sql);
			$service_row = $db_conn->getRow($service_sql);
			 if(!$service_row){
				$this->setError('Service `'.$serviceType.'` doesn\'t exist');
				return false;
			}
			$this->service = new Sushee_WebAPI($service_row);
		}
		
		return $this->service;
	}
	
	function getOauthConnection(){
		$service = $this->getWebAPI();
		$this->loadFields();
		$connection = new Sushee_Oauth($service->getField('Consumer_Key'), $service->getField('Consumer_Secret'),$this->getField('OAuth_Token'),$this->getField('OAuth_Token_Secret'));
		return $connection;
	}
}

// same interface as URL class, to be usable by GET WEBSERVICE 
class Sushee_WebAccountRequest extends sushee_Element{
	
	var $method = 'GET';
	var $params = array();
	var $account;
	var $url;
	
	function Sushee_WebAccountRequest($account,$url){
		$this->account = $account;
		$this->url = $url;
	}
	
	function getParams(){
		return $this->params;
	}
	
	function execute(){
		$connection = $this->account->getOauthConnection();
		if($connection){
			switch(strtolower($this->method)){
				case 'post':
					return $connection->post($this->url,$this->getParams());
					break;
				default:
					return $connection->get($this->url,$this->getParams());
			}
		}else{
			$this->setError('Could initiate connection to the webaccount');
			return false;
		}
		
	}
	
	function setMethod($method){
		$this->method = $method;
	}
	
	function addParam($name,$value){
		$this->params[$name] = $value;
	}
	
}

?>