<?php
/**
 * Api emails page
 *
 * This page allows users to import contacts
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		Index
 * @author		anandaraj_088at09
 * @copyright	Copyright (c) 2009 - 2010 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id:
 * @since 		2009-10-02
 */
/**
 * File having common configuration variables required for the entire project
 */

require_once('../common/configs/config.inc.php');
if ($CFG['admin']['module']['facebook'])
	{
		if (version_compare(PHP_VERSION,'5','>=')) {
			require_once ('../facebook/client/facebook.php');
		} else {
		 	require_once ('../facebook/php4client/facebook.php');
		  	require_once ('../facebook/php4client/facebookapi_php4_restlib.php');
		}
	}
$CFG['lang']['include_files'][] = 'languages/%s/'.$CFG['admin']['index']['anova_module'].'/api.emails.php';
$CFG['site']['is_module_page'] = $CFG['admin']['index']['anova_module'];
$CFG['html']['is_use_header'] = false;

$CFG['html']['header'] = 'general/html_header_popup.php';
$CFG['html']['footer'] = 'general/html_footer_popup.php';

$CFG['mods']['include_files'][] = 'common/classes/class_FormHandler.lib.php';
$CFG['mods']['include_files'][] = 'tools/yahoo_importer/lib/Yahoo.inc';

//partial optimization. Don't use DB unnecessarily ie, DB only needed when the form is submitted/posted.
$EmailApisDir = $CFG['site']['project_path'].'tools/email_apis/';

$yahooApisDir = $CFG['site']['project_path'].'tools/yahoo_importer/';

require_once($CFG['site']['project_path'].'common/configs/config_email_api.inc.php');
/**
 * File to include the header file, database access file, session management file, help file and necessary functions
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');
//-------------------------class EditProfileFormHandler-------------------->>>

class ApiEmails extends FormHandler
	{
		/**
		 * ApiEmails::$emails
		 * $emails array
		 */
		public $emails = array();

		/**
		 * ApiEmails::$yahooCheck
		 * $yahooCheck bool
		 */
		public $yahooCheck = false;

		/**
		 * ApiEmails::getInviteFriendsList()
		 *
		 */
		public function getInviteFriendsList()
			{
		 		  global $smartyObj;
				  $facebook = new Facebook($this->CFG['facebook']['api_key'], $this->CFG['facebook']['appsecret'], true);
				  $user = $facebook->require_login();
				  $fql = 'SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1='.$user.') AND has_added_app = 1';
				  $_friends = $facebook->api_client->fql_query($fql); // Extract the user ID's returned in the FQL request into a new array.

				  $friends = array();
				  if (is_array($_friends) && count($_friends))
					{
						 foreach ($_friends as $friend)
							{
								 $friends[] = $friend['uid'];
							}
					}

				 // echo "GGGGG".$req_friend = implode(',', $friends);
				  $added_friends='';
				  $y =count($friends);
				  for($i=0; $i<$y; $i++)
				  	{
						$added_friends .= $friends[$i].',';
					}
				  if(substr($added_friends, 0, -1) == ',')
				  	$added_friends = substr($added_friends, 0, -1);

				  $smartyObj->assign('facebook_friends', $added_friends);
			}

		/**
		 * ApiEmails::getYahooUrl()
		 * To get yahoo url
		 * @return
		 * @access public
		 */
		public function getYahooUrl()
			{
				$appid = $this->CFG['admin']['email_api']['yahoo_appid']; // my application ID, obtained at registration
				$consumer_key = $this->CFG['admin']['email_api']['yahoo_consumer'];// my consumer key, obtained at registration
				$secret_key = $this->CFG['admin']['email_api']['yahoo_secret']; // my shared secret, obtained at registration

				$callback = YahooUtil::current_url()."?in_popup";

				// pass the credentials to get an auth url.
				// this URL will be used for the pop-up.
  				$auth_url = YahooSession::createAuthorizationUrl($consumer_key, $secret_key, $callback);

  				if($auth_url)
  					{
  						$this->yahooCheck = true;
					}
				return htmlspecialchars($auth_url);
			}

		/**
		 * ApiEmails::getGmailUrl()
		 * To get gmail url
		 * @return
		 * @access public
		 */
		public function getGmailUrl()
			{
				$next = $this->CFG['site']['url'].$this->CFG['admin']['index']['anova_module'].'/api.emails.php';
				$next = urlencode($next);
				$scope = urlencode('http://www.google.com/m8/feeds/');
				$url = 'https://www.google.com/accounts/AuthSubRequest?scope='.$scope.'&session=0&secure=0&next='.$next;

				return htmlspecialchars($url);

			}

		/**
		 * ApiEmails::get_yahoo_credentials()
		 * To get yahoo details
		 * @param mixed $url
		 * @return array
		 * @access public
		 */
		public function get_yahoo_credentials( $url )
			{
			  $ch = curl_init();
			  curl_setopt( $ch, CURLOPT_URL, $url );
			  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
			  $store = curl_exec( $ch );
			  $xml = curl_exec( $ch );

			  if (  preg_match( "/(Y=.*)/", $xml, $match_array ) == 1 ) {
			    $COOKIE = $match_array[1];
			  }
			  if (  preg_match( "/<WSSID>(.+)<\/WSSID>/", $xml, $match_array ) == 1 ) {
			    $WSSID = $match_array[1];
			  }
			  if (  preg_match( "/<Timeout>(.+)<\/Timeout>/", $xml, $match_array ) == 1 ) {
			    $timeout = $match_array[1];
			  }

			  $rv = array();
			  $rv["COOKIE"] = $COOKIE;
			  $rv["WSSID"] = $WSSID;
			  $rv["timeout"]   = $timeout;
			  return $rv;
			}

		/**
		 * ApiEmails::getLiveUrl()
		 * To get live url
		 * @return mixed
		 * @access public
		 */
		public function getLiveUrl()
			{
				global $CFG, $EmailApisDir;
				$msnDir = $EmailApisDir.'msn/';
				$KEYFILE = $CFG['site']['project_path'].'common/configs/Application-Key.xml';
				require_once $msnDir.'lib/windowslivelogin.php';
				$wll = WindowsLiveLogin::initFromXml($KEYFILE);
				$wll->setDebug(true);
				//Get the consent URL for the specified offers.
				$consenturl = $wll->getConsentUrl('Contacts.View');
				return htmlspecialchars($consenturl);
			}

		/**
		 * ApiEmails::get_yahoo_contacts_from_xml()
		 * Get yahoo mail contact using xml
		 * @param string $xml
		 * @return array email
		 * @access public
		 */
		public function get_yahoo_contacts_from_xml($xml = '')
			{
				$obj = simplexml_load_string($xml);
				$return = array();

				foreach($obj->contact as $contact)
					{
						$email = (string)@$contact->email;
						$first = (string)@$contact->name->first;
						$last = (string)@$contact->name->last;
						$name = $first;
						$name .= ($first and $last)?' ':'';
						$name .= $last;
						if ($email)
							{
								$return[$email] = $name?$name:$email;
							}
					}
				return $return;
			}

		/**
		 * ApiEmails::get_gmail_contacts_from_xml()
		 * Get  gmail contact using xml
		 * @param string $xml
		 * @return array email
		 * access public
		 */
		public function get_gmail_contacts_from_xml($xml = '')
			{
				$return = array();
				$feed = simplexml_load_string($xml);
				if ($feed)
					{
						$names = $emails = array();
						$ns = $feed->xpath('//gd:email');
						foreach($ns as $sim)
							{
								$emails[] = (string)$sim['address'];
							}
						$children = $feed->children('http://www.w3.org/2005/Atom');
						$entries = $children->entry;
						foreach ($entries as $entry) {
						 	$details = $entry->children('http://www.w3.org/2005/Atom');
						 	$names[] = (string)$details->title;
						}


						foreach($emails as $key=>$email)
							{
								$display = $email;
								if (isset($names[$key]) and $names[$key])
									{
										$display = $names[$key];
									}
								$return[$email] = $display;
							}
					}
				return $return;
			}

		/**
		 * ApiEmails::hexaTo64SignedDecimal()
		 *
		 * @param mixed $hexa
		 * @return
		 * access public
		 */
		public function hexaTo64SignedDecimal($hexa)
			{
			    $bin = unfucked_base_convert($hexa, 16, 2);
			    if (64 === strlen($bin) and 1 == $bin[0])
			    {
			        $inv_bin = strtr($bin, '01', '10');
			        $i = 63;
			        while (0 !== $i)
			        {
			            if (0 == $inv_bin[$i])
			            {
			                $inv_bin[$i] = 1;
			                $i = 0;
			            }
			            else
			            {
			                $inv_bin[$i] = 0;
			                $i--;
			            }
			        }
			        return '-' . unfucked_base_convert($inv_bin, 2, 10);
			    }
			    else
			    {
			        return unfucked_base_convert($hexa, 16, 10);
			    }
			}

		/**
		 * ApiEmails::fetchLiveContacts()
		 *
		 * @param mixed $dt
		 * @param mixed $lid
		 * @return mixed
		 * @access public
		 */
		public function fetchLiveContacts($dt, $lid)
			{
				$uri = "https://livecontacts.services.live.com/@C@$lid/REST/LiveContacts/contacts";
				// Add the token to the header
				$headers = array
				(
					"Authorization: DelegatedToken dt=\"$dt\""
					//"Authorization: DelegationToken dt=\"$dt\""
				);
				// I use cURL (www.php.net/curl) to get the information
				// Let's set up the request
				$curl = curl_init();
				curl_setopt($curl, CURLOPT_URL, $uri);
				curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($curl, CURLOPT_TIMEOUT, 60);
				curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
				curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
				curl_setopt($curl, CURLOPT_USERAGENT, "Agriya - Product - Live API Integration");
				// Ready? Set? GO!
				$data = curl_exec($curl);
				// Get the info and close the connection
				$curlinfo = curl_getinfo($curl);
				curl_close($curl);
				// Have any errors occured? If so, print them.
				if($curlinfo["http_code"] == "401")
					{
						echo "<h2>The remote server refused the DT. Is it correct?</h2>";
						echo "<h3>Sometimes this error may occur. If you're sure everything is correct, try again.</h3>";
						return false;
					}
				if($curlinfo["http_code"] == "403")
					{
						echo "<h2>The remote server refused to give you this information. Are you sure you have selected the mode belonging to the requested offer (i.e. Contacts for Contacts.View)</h2>";
						return false;
					}
				if($curlinfo["http_code"] == "404")
					{
						echo "<h2>Woops... looks like you're trying to request something that isn't there. Are you sure the CID and LID are ok?</h2>";
						return false;
					}
				// If the code reaches this point, everything went well.
				return $data;
			}

		/**
		 * ApiEmails::get_msn_contacts_from_xml()
		 * To get msn users from xml
		 * @param string $xml
		 * @return
		 * @access public
		 */
		public function get_msn_contacts_from_xml($xml = '')
			{
				$obj = simplexml_load_string($xml);
				$return = array();
				foreach($obj->Contact as $contact)
					{
						$email = (string)@$contact->Emails->Email->Address;
						$first = (string)@$contact->Profiles->Personal->FirstName;
						$last = (string)@$contact->Profiles->Personal->LastName;
						$name = $first;
						$name .= ($first and $last)?' ':'';
						$name .= $last;
						if ($email)
							{
								$return[$email] = $name?$name:$email;
							}
					}
				return $return;
			}


		/**
		 * ApiEmails::get_yahoo_contacts_from_api()
		 *
		 * @param mixed $user_contacts
		 * @return
		 */
		public function get_yahoo_contacts_from_api($user_contacts)
			{
				$return = array();

				foreach($user_contacts as $contact)
					{
						foreach($contact as $obj)
							{
								if(is_array($obj))
									{
										foreach($obj as $element)
											{
												foreach($element->fields as $field)
													{
														if(!is_string($field))
															{
																if($field->type == 'email')
																	{
																		$email = $field->value;
																	}
																if($email && isset($field->value->givenName) && strlen($field->value->givenName)>0)
																	{
																		$first_name = $field->value->givenName;
																		$last_name = $field->value->familyName;

																		$name = $first_name . ' ' . $last_name;

																		if($name != ' ')
																			{
																				$return[$email] = $name?$name:$email;

																				$email = '';
																				$name = '';

																			}
																	}
															}
													}
											}
									}
							}
					}
				return $return;
			}

		/**
		 * ApiEmails::chkYahooAccess()
		 *
		 * @return
		 */
		public function chkYahooAccess()
			{
				$appid = $this->CFG['admin']['email_api']['yahoo_appid']; // my application ID, obtained at registration
				$consumer_key = $this->CFG['admin']['email_api']['yahoo_consumer'];// my consumer key, obtained at registration
				$secret_key = $this->CFG['admin']['email_api']['yahoo_secret']; // my shared secret, obtained at registration

				$hasSession = YahooSession::hasSession($consumer_key, $secret_key, $appid);

				if($hasSession)
				 {
				 	 YahooSession::clearSession();
				 }
				$callback = YahooUtil::current_url()."?in_popup";

				// pass the credentials to get an auth url.
				// this URL will be used for the pop-up.
  				$auth_url = YahooSession::createAuthorizationUrl($consumer_key, $secret_key, $callback);

  				if($auth_url)
  					{
  						$this->yahooCheck = true;
					}
			}

	}
//--------------------Code begins-------------->>>>>//
$apiEmails = new ApiEmails();
if( isMember() && chkAllowedModule(array('facebook')))
	{
		if($facebook_user = $apiEmails->isFacebookUser())
			{
				$apiEmails->getInviteFriendsList();
			}
		$smartyObj->assign('facebook_user', $facebook_user);
	}
else
	$smartyObj->assign('facebook_user', '');

$apiEmails->setPageBlockNames(array('form_imported_emails'));
$smartyObj->assign('forum_details','');
$smartyObj->assign('question_details','');
$apiEmails->setFormField('token','');
$apiEmails->setFormField('ask', '');
$apiEmails->setFormField('value', '');
$apiEmails->setFormField('appid','');
$apiEmails->sanitizeFormInputs($_REQUEST);
if($apiEmails->getFormField('ask') == 'question')
   {
		if($apiEmails->getFormField('value'))
			{
				$content_details = $apiEmails->getQuestionDetails($apiEmails->getFormField('value'));
				$smartyObj->assign('question_details', $content_details['qLink']);
			}
   }
elseif($apiEmails->getFormField('ask') == 'forum')
   {
		if($apiEmails->getFormField('value'))
			{
				$content_details = $apiEmails->getForumDetails($apiEmails->getFormField('value'));
				$smartyObj->assign('forum_details', $content_details['f_link']);
			}
   }
$apiEmails->setAllPageBlocksHide();
$display_email = '';
$apiEmails->msnCheck = function_exists('mhash') && $CFG['feature']['msn'];
$smartyObj->assign('ask', $apiEmails->getFormField('ask'));
$smartyObj->assign('value', $apiEmails->getFormField('value'));
if( isMember() && chkAllowedModule(array('facebook')))
	$smartyObj->assign('facebook_user', $apiEmails->IsFacebookUser());
else
	$smartyObj->assign('facebook_user', '');
if (!$apiEmails->isFormGETed($_GET, 'oauth_token') && !$apiEmails->isFormGETed($_GET, 'token'))
	{
		$apiEmails->chkYahooAccess();
	}

if ($apiEmails->isFormGETed($_GET, 'oauth_token'))
	{
		$session = YahooSession::requireSession($CFG['admin']['email_api']['yahoo_consumer'], $CFG['admin']['email_api']['yahoo_secret'], $CFG['admin']['email_api']['yahoo_appid']);
		if($session)
			{
				$start = 0;
			  	$count = 50;
			    // Get the currently sessioned user.
			    $user = $session->getSessionedUser();

			    $user_contacts = $user->getContacts($start,$count);

			    $apiEmails->emails = $apiEmails->get_yahoo_contacts_from_api($user_contacts);

			    YahooSession::clearSession();

			    $apiEmails->setPageBlockShow('form_imported_emails');
			}

	}
else if ( $apiEmails->isFormGETed($_GET, 'token'))
	{
		$contacts = 'http://www.google.com/m8/feeds/contacts/default/full';
		$ch = curl_init();
		$headers = array();
		$headers[] = 'Authorization: AuthSub token="'.$apiEmails->getFormField('token').'"';

		curl_setopt($ch, CURLOPT_URL, $contacts);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$html = curl_exec($ch);
		$apiEmails->emails = $apiEmails->get_gmail_contacts_from_xml($html);
		$apiEmails->setPageBlockShow('form_imported_emails');
	}
elseif (isset($_POST['ConsentToken']))
	{
		$msnDir = $EmailApisDir.'msn/';
		require_once $msnDir.'lib/windowslivelogin.php';
		$KEYFILE = $CFG['site']['project_path'].'common/configs/Application-Key.xml';

		// Initialize the WindowsLiveLogin module.
		$wll = WindowsLiveLogin::initFromXml($KEYFILE);
		$wll->setDebug(true);
		$msnTokens = $wll->processConsent($_POST);
		$lid = $apiEmails->hexaTo64SignedDecimal($msnTokens->getLocationID());
		$data = $apiEmails->fetchLiveContacts($msnTokens->getDelegationToken(), $lid);
		if ($data)
			{
				$apiEmails->emails = $apiEmails->get_msn_contacts_from_xml($data);
				$apiEmails->setPageBlockShow('form_imported_emails');
			}
	}
//--------------------Page block templates begins-------------------->>>>>//
$apiEmails->includeHeader();
setTemplateFolder('root', $CFG['admin']['index']['anova_module']);
$smartyObj->display('api.emails.tpl');
$apiEmails->includeFooter();
?>