how to get ticket details of multiple ticket IDs through OTRS REST URL - rest

Currently i used this URL for single ticket ID: http:///otrs/nph-genericinterface.pl/Webservice/GenericTicketConnectorREST/Ticket/2020?UserLogin=abc&Password=abc123&DynamicFields=1
How can i pass multiple ticket IDs into this URL..

You can't. You should just use a loop in your code and make a call to the web service for each TicketID.

Here is the example of otrs6 rest api with generic interface for ticketget
<?php
require_once 'otrs6composer/vendor/autoload.php';
Unirest\Request::defaultHeader("Accept", "application/json");
Unirest\Request::defaultHeader("Content-Type", "application/json");
Unirest\Request::verifyPeer(true);
function otrs_ticket_detail_listing($ticket) {
$title = "";
$state = "";
$type = "";
$queue = "";
$output = "";
$TicketNr = $ticket;
$BaseURL2 = 'http://10.247.142.10/otrs/nph-genericinterface.pl/Webservice/TicketConGeneric/TicketGet';
$BaseURL1 = 'http://10.247.142.10/otrs/nph-genericinterface.pl/Webservice/TicketConGeneric/Session/SessionCreate';
$headers = [];
$body = json_encode(
[
"UserLogin" => "root#localhost",
"Password" => "nic123",
]
);
/**
* SessionCreate
*
* http://doc.otrs.com/doc/api/otrs/stable/Perl/Kernel/GenericInterface/Operation/Session/SessionCreate.pm.html
*/
$response = Unirest\Request::post($BaseURL1, $headers, $body);
if (!$response->body->SessionID) {
print "No SessionID returnd \n";
exit(1);
}
$SessionID = $response->body->SessionID;
/**
* TicketGet
*
* http://doc.otrs.com/doc/api/otrs/stable/Perl/Kernel/GenericInterface/Operation/Ticket/TicketGet.pm.html
*/
$param = [
'SessionID' => $SessionID,
];
$ArticleGet = Unirest\Request::get($BaseURL2."/".$TicketNr, $headers, $param);
return $ArticleGet;
//var_dump($response);
}
?>

Related

Magento2: how to get the SKUs from the serialized condition in cart price rules

I need to get the SKUs from cart price rule to assign a specific attribute to them, but the condition is saved in the database serialized, and I want to make foreach loop to extract all the SKU's from the serialized condition :
?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
foreach ($rules as $rule) {
echo $rule->getConditionsSerialized() . "\n";
}
and the result of the serialized condition is:
{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Combine","attribute":null,"operator":null,"value":1,"is_value_processed":null,"aggregator":"all","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product\\Subselect","attribute":"qty","operator":">=","value":"1","is_value_processed":null,"aggregator":"any","conditions":[{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817069","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817051","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817561","is_value_processed":false,"attribute_scope":null},{"type":"Magento\\SalesRule\\Model\\Rule\\Condition\\Product","attribute":"sku","operator":"==","value":"100817579","is_value_processed":false,"attribute_scope":null}]}]}
so, how can we extract all the SKU's from this condition.
thanks in advance.
try something like this:
<?php
ini_set('display_errors', '1');
ini_set('error_reporting', E_ALL);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/../app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objrules = $obj->create('Magento\SalesRule\Model\RuleFactory')->create();
$rules = $objrules->getCollection()->addFieldToFilter("is_active", "1");
$skus = [];
if ($rules) {
foreach ($rules as $rule) {
$ruleData = $rule->getConditionsSerialized();
if ($ruleData) {
$ruleDataArray = json_decode($ruleData, true);
if (isset($ruleDataArray['conditions'])) {
$conditions = $ruleDataArray['conditions'];
foreach ($conditions as $condition) {
if (isset($condition['conditions'])) {
$productConditions = $condition['conditions'];
foreach ($productConditions as $productCondition) {
if (isset($productCondition['value'])) {
$skuValues = $productCondition['value'];
$skuValues = explode(",",$skuValues);
foreach ($skuValues as $skuValue) {
$skus[] = $skuValue;
}
}
}
}
}
}
}
}
}
$uniqSkus = array_unique($skus);
print_r($uniqSkus);
exit;

HWIOAuthBundle Symfony2 get user likes from Facebook

In my project I use FOSUserBundle and HWIOAuthBundle for user authentification. integrated HWIOAuthBundle using this tutorial. But additionaly I need to get user likes. I've already added user_likes in a scope and when I try to login facebook says that I want to get user likes but how do I get those likes for example in a Service. Maybe in a FOSUBUserProvider.php which was created in the link I provided above.
FOSUBUserProvider.php
<?php
namespace Atotrukis\MainBundle\Service;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
class FOSUBUserProvider extends BaseClass
{
/**
* {#inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response)
{
$property = $this->getProperty($response);
$username = $response->getUsername();
//on connect - get the access token and the user ID
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
//we "disconnect" previously connected users
if (null !== $previousUser = $this->userManager->findUserBy(array($property => $username))) {
$previousUser->$setter_id(null);
$previousUser->$setter_token(null);
$this->userManager->updateUser($previousUser);
}
//we connect current user
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
$this->userManager->updateUser($user);
}
/**
* {#inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$email = $response->getEmail();
$name = $response->getRealName();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
//when the user is registrating
if (null === $user) {
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
// create new user here
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
//I have set all requested data with the user's username
//modify here with relevant data
$user->setName($name);
$user->setUsername($email);
$user->setEmail($email);
$user->setPlainPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
}
To call facebook API i use facebook sdk and for example to get friends, I added this to my controller:
$user = $this->getUser();
if ($user && $accessToken = $user->getFacebookAccessToken())
{
$friends= [];
$userRepo = $this->getUserRepository();
$session = new FacebookSession($accessToken);
$session->setDefaultApplication($this->container->getParameter('facebook_client_id'), $this->container->getParameter('facebook_client_secret'));
$friendsData = (new FacebookRequest(
$session, 'GET', '/me/friends'))->execute()->getGraphObject()->asArray();
foreach ($friendsData['data'] as $friendData) {
$friend = $userRepo->findOneByFacebookId($friendData->id);
if ($friend) {
$friends[] = $userRepo->findOneByFacebookId($friendData->id);
}
}
return array(
'user' => $user,
'friends' => $friends
);
}

Notification.php for Windows Azure notification hub API using PHP

I want to send the notification, using windows azure notification hub api in PHP.
You have to interface directly with REST (http://msdn.microsoft.com/en-us/library/dn495827.aspx).
The code you will have to write is basically this one:
class Notification {
public $format;
public $payload;
# array with keynames for headers
# Note: Some headers are mandatory: Windows: X-WNS-Type, WindowsPhone: X-NotificationType
# Note: For Apple you can set Expiry with header: ServiceBusNotification-ApnsExpiry in W3C DTF, YYYY-MM-DDThh:mmTZD (for example, 1997-07-16T19:20+01:00).
public $headers;
function __construct($format, $payload) {
if (!in_array($format, ["template", "apple", "windows", "gcm", "windowsphone"])) {
throw new Exception('Invalid format: ' . $format);
}
$this->format = $format;
$this->payload = $payload;
}
}
class NotificationHub {
const API_VERSION = "?api-version=2013-10";
private $endpoint;
private $hubPath;
private $sasKeyName;
private $sasKeyValue;
function __construct($connectionString, $hubPath) {
$this->hubPath = $hubPath;
$this->parseConnectionString($connectionString);
}
private function parseConnectionString($connectionString) {
$parts = explode(";", $connectionString);
if (sizeof($parts) != 3) {
throw new Exception("Error parsing connection string: " . $connectionString);
}
foreach ($parts as $part) {
if (strpos($part, "Endpoint") === 0) {
$this->endpoint = "https" . substr($part, 11);
} else if (strpos($part, "SharedAccessKeyName") === 0) {
$this->sasKeyName = substr($part, 20);
} else if (strpos($part, "SharedAccessKey") === 0) {
$this->sasKeyValue = substr($part, 16);
}
}
}
private function generateSasToken($uri) {
$targetUri = strtolower(rawurlencode(strtolower($uri)));
$expires = time();
$expiresInMins = 60;
$expires = $expires + $expiresInMins * 60;
$toSign = $targetUri . "\n" . $expires;
$signature = rawurlencode(base64_encode(hash_hmac('sha256', $toSign, $this->sasKeyValue, TRUE)));
$token = "SharedAccessSignature sr=" . $targetUri . "&sig="
. $signature . "&se=" . $expires . "&skn=" . $this->sasKeyName;
return $token;
}
public function broadcastNotification($notification) {
$this->sendNotification($notification, "");
}
public function sendNotification($notification, $tagsOrTagExpression) {
if (is_array($tagsOrTagExpression)) {
$tagExpression = implode(" || ", $tagsOrTagExpression);
} else {
$tagExpression = $tagsOrTagExpression;
}
# build uri
$uri = $this->endpoint . $this->hubPath . "/messages" . NotificationHub::API_VERSION;
$ch = curl_init($uri);
if (in_array($notification->format, ["template", "apple", "gcm"])) {
$contentType = "application/json";
} else {
$contentType = "application/xml";
}
$token = $this->generateSasToken($uri);
$headers = [
'Authorization: '.$token,
'Content-Type: '.$contentType,
'ServiceBusNotification-Format: '.$notification->format
];
if ("" !== $tagExpression) {
$headers[] = 'ServiceBusNotification-Tags: '.$tagExpression;
}
# add headers for other platforms
if (is_array($notification->headers)) {
$headers = array_merge($headers, $notification->headers);
}
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $notification->payload
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
throw new Exception(curl_error($ch));
}
$info = curl_getinfo($ch);
if ($info['http_code'] <> 201) {
throw new Exception('Error sending notificaiton: '. $info['http_code'] . ' msg: ' . $response);
}
}
}
And use it this way: initialize your Notification Hubs client (substitute the connection string and hub name as instructed in the Get started tutorial):
$hub = new NotificationHub("connection string", "hubname");
Then add the send code depending on your target mobile platform.
Windows Store and Windows Phone 8.1 (non-Silverlight)
$toast = '<toast><visual><binding template="ToastText01"><text id="1">Hello from PHP!</text></binding></visual></toast>';
$notification = new Notification("windows", $toast);
$notification->headers[] = 'X-WNS-Type: wns/toast';
$hub->sendNotification($notification);
iOS
$alert = '{"aps":{"alert":"Hello from PHP!"}}';
$notification = new Notification("apple", $alert);
$hub->sendNotification($notification);
Android
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("gcm", $message);
$hub->sendNotification($notification);
Windows Phone 8.0 and 8.1 Silverlight
$toast = '<?xml version="1.0" encoding="utf-8"?>' .
'<wp:Notification xmlns:wp="WPNotification">' .
'<wp:Toast>' .
'<wp:Text1>Hello from PHP!</wp:Text1>' .
'</wp:Toast> ' .
'</wp:Notification>';
$notification = new Notification("mpns", $toast);
$notification->headers[] = 'X-WindowsPhone-Target : toast';
$notification->headers[] = 'X-NotificationClass : 2';
$hub->sendNotification($notification);
Kindle Fire
$message = '{"data":{"msg":"Hello from PHP!"}}';
$notification = new Notification("adm", $message);
$hub->sendNotification($notification);
For registration management you have to follow the content formats shown in the MSDN topic linked above, and probably do some nasty xml parsing... Be warned that element order is important and things will not work if the element are out of order.

getting yahoo contacts in php (yahoo OAuth)

I'm developing an invite_friends tool for a website. I read these articles and taken the steps:
http://anandafit.info/2011/01/06/yahoo-contact-list-reader-in-php/
http://nullinfo.wordpress.com/oauth-yahoo/
but when i execute that, at the end, Yahoo says:
{ "error": { "lang": "en-US", "description": "Please provide valid credentials. OAuth oauth_problem=\"token_rejected\", realm=\"yahooapis.com\"" } }
:((
These are my codes:
getreqtok.php
<?php
require 'modules/invite/yahoo/globals.php';
require 'modules/invite/yahoo/oauth_helper.php';
// Callback can either be 'oob' or a url whose domain must match
// the domain that you entered when registering your application
$callback='http://www.warzone.in/modules.php?name=invite&op=yahoo_get_contacts';
// Get the request token using HTTP GET and HMAC-SHA1 signature
$retarr = get_request_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$callback, false, true, true);
//echo $retarr[3]["oauth_token_secret"]."<br>
//<br>
//";
session_start();
$_SESSION["oauth_token_secret"] = $retarr[3]["oauth_token_secret"];
//echo $_SESSION["oauth_token_secret"]."<br>
//<br>
//<br>
//";
if (! empty($retarr)){
list($info, $headers, $body, $body_parsed) = $retarr;
if ($info['http_code'] == 200 && !empty($body)) {
//print "Have the user go to xoauth_request_auth_url to authorize your app\n";
?>
YAHOO
<?php
}
}
/**
* Get a request token.
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $callback callback url can be the string 'oob'
* #param bool $usePost use HTTP POST instead of GET
* #param bool $useHmacSha1Sig use HMAC-SHA1 signature
* #param bool $passOAuthInHeader pass OAuth credentials in HTTP header
* #return array of response parameters or empty array on error
*/
function get_request_token($consumer_key, $consumer_secret, $callback, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=false)
{
$retarr = array(); // return value
$response = array();
$url = 'https://api.login.yahoo.com/oauth/v2/get_request_token';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_callback'] = $callback;
// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, null);
} else {
$params['oauth_signature_method'] = 'PLAINTEXT';
$params['oauth_signature'] =
oauth_compute_plaintext_sig($consumer_secret, null);
}
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, FALSE);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("getreqtok:INFO:request_url:$request_url");
logit("getreqtok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("getreqtok:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit("getreqtok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $retarr;
}
?>
getacctok.php
<?php
session_start();
require 'modules/invite/yahoo/globals.php';
require 'modules/invite/yahoo/oauth_helper.php';
// Fill in the next 3 variables.
$request_token=$_REQUEST["oauth_token"];
$request_token_secret=$_SESSION["oauth_token_secret"];
$oauth_verifier= $_REQUEST["oauth_verifier"];
//echo $request_token." xxxx ".$request_token_secret." yyyy ".$oauth_verifier."<br>
//<br>
//<br>
//";
// Get the access token using HTTP GET and HMAC-SHA1 signature
$retarr = get_access_token(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$request_token, $request_token_secret,
$oauth_verifier, false, true, true);
if (! empty($retarr)) {
list($info, $headers, $body, $body_parsed) = $retarr;
if ($info['http_code'] == 200 && !empty($body)) {
// print "Use oauth_token as the token for all of your API calls:\n" .
rfc3986_decode($body_parsed['oauth_token']);
}
}
/**
* Get an access token using a request token and OAuth Verifier.
* #param string $consumer_key obtained when you registered your app
* #param string $consumer_secret obtained when you registered your app
* #param string $request_token obtained from getreqtok
* #param string $request_token_secret obtained from getreqtok
* #param string $oauth_verifier obtained from step 3
* #param bool $usePost use HTTP POST instead of GET
* #param bool $useHmacSha1Sig use HMAC-SHA1 signature
* #param bool $passOAuthInHeader pass OAuth credentials in HTTP header
* #return array of response parameters or empty array on error
*/
function get_access_token($consumer_key, $consumer_secret, $request_token, $request_token_secret, $oauth_verifier, $usePost=false, $useHmacSha1Sig=true, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();
$url = 'https://api.login.yahoo.com/oauth/v2/get_token';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_token']= $request_token;
$params['oauth_verifier'] = $oauth_verifier;
// compute signature and add it to the params list
if ($useHmacSha1Sig) {
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, $request_token_secret);
} else {
$params['oauth_signature_method'] = 'PLAINTEXT';
$params['oauth_signature'] =
oauth_compute_plaintext_sig($consumer_secret, $request_token_secret);
}
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, false);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("getacctok:INFO:request_url:$request_url");
logit("getacctok:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 443, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("getacctok:INFO:request_url:$request_url");
$response = do_get($request_url, 443, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
$body_parsed = oauth_parse_str($body);
if (! empty($body_parsed)) {
logit("getacctok:INFO:response_body_parsed:");
//print_r($body_parsed);
}
$retarr = $response;
$retarr[] = $body_parsed;
}
return $retarr;
}
$guid = $retarr[3]["xoauth_yahoo_guid"];
$access_token = $retarr[3]["oauth_token"];
$access_token_secret = $retarr[3]["oauth_token_secret"];
// Call Contact API
$retarr = callcontact(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET,
$guid, $access_token, $access_token_secret,
false, true);
function callcontact($consumer_key, $consumer_secret, $guid, $access_token, $access_token_secret, $usePost=false, $passOAuthInHeader=true)
{
$retarr = array(); // return value
$response = array();
$url = 'http://social.yahooapis.com/v1/user/' . $guid . '/contacts;count=5';
$params['format'] = 'json';
$params['view'] = 'compact';
$params['oauth_version'] = '1.0';
$params['oauth_nonce'] = mt_rand();
$params['oauth_timestamp'] = time();
$params['oauth_consumer_key'] = $consumer_key;
$params['oauth_token'] = $access_token;
// compute hmac-sha1 signature and add it to the params list
$params['oauth_signature_method'] = 'HMAC-SHA1';
$params['oauth_signature'] =
oauth_compute_hmac_sig($usePost? 'POST' : 'GET', $url, $params,
$consumer_secret, $access_token_secret);
// Pass OAuth credentials in a separate header or in the query string
if ($passOAuthInHeader) {
$query_parameter_string = oauth_http_build_query($params, true);
$header = build_oauth_header($params, "yahooapis.com");
$headers[] = $header;
} else {
$query_parameter_string = oauth_http_build_query($params);
}
// POST or GET the request
if ($usePost) {
$request_url = $url;
logit("callcontact:INFO:request_url:$request_url");
logit("callcontact:INFO:post_body:$query_parameter_string");
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$response = do_post($request_url, $query_parameter_string, 80, $headers);
} else {
$request_url = $url . ($query_parameter_string ?
('?' . $query_parameter_string) : '' );
logit("callcontact:INFO:request_url:$request_url");
$response = do_get($request_url, 80, $headers);
}
// extract successful response
if (! empty($response)) {
list($info, $header, $body) = $response;
if ($body) {
logit("callcontact:INFO:response:");
print(json_pretty_print($body));
}
$retarr = $response;
}
return $retarr;
}
?>
class YahooContacts
{
protected static $oauthConsumerKey ="";
protected static $OauthConsumerSecret ="";
protected static $oauthDomain="";
public function __construct(){
//Check Session is Start Or not
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
/**
* Authentication user And Access Refresh and access token
*
* #author <Pawan Kumar>
* #return type boolean
**/
protected function getAuthorization($code)
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$data="grant_type=authorization_code&redirect_uri=".self::$oauthDomain."&code=".$code;
$auth = base64_encode(self::$oauthConsumerKey.":".self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic '.$auth,
'Content-Type: application/x-www-form-urlencoded'
);
try{
$resultSet =self::makeRequest($url,$data,$headers);
if($resultSet->access_token){
$this->setAccessToken($resultSet->access_token);
$this->setRefreshToken($resultSet->refresh_token);
$this->setGuidToken($resultSet->xoauth_yahoo_guid);
return true;
}
}catch(Exception $ex){
throw($ex);
}
}
/**
* Get All Contacts list From Yahoo API using Auth Access Token And oAuth Guid Token
*
* #author <Pawan Kumar>
* #return type Object
**/
public function getUserContactsDetails()
{
/** Refresh Access Token is Expired **/
$this->generateAccessToken();
$guid =$this->getGuidToken();
$token =$this->getAccessToken();
$contactUrl="https://social.yahooapis.com/v1/user/$guid/contacts?format=json";
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: Bearer $token"
)
);
$context = stream_context_create($opts);
$file = file_get_contents($contactUrl, false, $context);
$output =json_decode($file);
return $output;
}
/**
* Get New Access Token using Refresh Token
*
* #author <Pawan Kumar>
* #return type boolean
**/
protected function generateAccessToken()
{
$url = "https://api.login.yahoo.com/oauth2/get_token";
$refreshToken = $this->getRefreshToken();
$data="grant_type=refresh_token&redirect_uri=".self::$oauthDomain."&refresh_token=".$refreshToken;
$auth = base64_encode(self::$oauthConsumerKey.":".self::$OauthConsumerSecret);
$headers = array(
'Authorization: Basic '.$auth,
'Content-Type: application/x-www-form-urlencoded'
);
try{
$resultSet =self::makeRequest($url,$data,$headers);
if($resultSet->access_token){
$this->setAccessToken($resultSet->access_token);
return true;
}else{
return false;
}
}catch(Exception $ex){
throw($ex);
}
}
/**
* Build a login url using oAuth Consumber Key And Redirect Domain
*
* #author Pawan Kumar
* #return type String
**/
public static function getLoginUrl()
{
$loginUrl = "https://api.login.yahoo.com/oauth2/request_auth";
$buildUrl =$loginUrl."?client_id=".self::$oauthConsumerKey."&redirect_uri=".self::$oauthDomain."&response_type=code&language=en-us";
return $buildUrl;
}
/**
* Make a Remote Post Request using MakeRequest Function
*
* #param Url String
* #param $postData String Send Post Data With Request
* #param headers Array Contain Auth basic information
* #author Pawan Kumar
* #return type Object
**/
public static function makeRequest($url,$postData,$headers){
try{
if (empty($url))throw new Exception("Url is Not Format.");
if (empty($postData))throw new Exception("Post Parameters is Not Defined");
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
curl_setopt($ch, CURLOPT_URL,$url);
$result = curl_exec($ch);
$output =json_decode($result);
return $output;
}catch(\Exception $ex){
throw($ex);
}
}
/**
* #param RefreshToken to set String Token Into Session
*/
public function setRefreshToken($token)
{
$_SESSION['refresh_token']=$token;
}
/**
* #return String Refresh Token From Session
*/
public function getRefreshToken()
{
return $_SESSION['refresh_token'];
}
/**
* #param AccessToken to set String Token into Session
*/
public function setAccessToken($token)
{
$_SESSION['access_token']=$token;
}
/**
* #return String Access Token From Session
*/
public function getAccessToken()
{
return $_SESSION['access_token'];
}
/**
* #param GuidToken to set String Token into Session
*/
public function setGuidToken($token)
{
$_SESSION['xoauth_yahoo_guid']=$token;
}
/**
* #return String Guid Token from Session
*/
public function getGuidToken()
{
return $_SESSION['xoauth_yahoo_guid'];
}
}
// Initialize Session If Session is Not Start
session_start();
if(isset($_GET['code'])){
$code = $_GET['code'];
if(!empty($code)){
// create a instance of yahoo contacts
$obj = new YahooContacts();
//Successfully Authorization Process
$obj->getAuthorization($code);
Header("Location:http://yahoo.fansunite.com.au");die;
}
}else{
if(isset($_SESSION['access_token'])){
// create a instance of yahoo contacts
$obj = new YahooContacts();
//After Authorization Get User Contacts Email
$res = $obj->getUserContactsDetails();
print "<pre>";
print_r($res);
}else{
$url = YahooContacts::getLoginUrl();
echo "<center><strong><a href='$url'>Login With Yahoo Mail !</a></strong></center>";
}
}

How to redirect to previous URL after login

I want to make redirection after login action to previous URL. Please tell me how to do that?
Store the page before Login into Session, After login , read the previous page url from the session and redirect the use to that page.
You can pass the "return" URL as a parameter to the login page. i.e http://yourserver.com/login/?return=http%3a%2f%2fyourserver.com%2fsomedir%2fsomething%2f. After a successful login you then use the get parameter to redirect by using a simple HTTP header location:http://yourserver.com/somedir/something/.
This is, for example, practiced in different Google and Microsoft services where there is a single page for signing in and different services that require the user to be loogged in.
You may this use Action helper I wrote some time ago. Cheers!
class Your_Controller_Action_Helper_GoBack
extends Zend_Controller_Action_Helper_Abstract
{
/**
* #todo Check if redirecting to the same domain
* #param bool $required Throw exception?
* #param bool $validateDomain
* #param bool $allowSubdomain
* #param string $alternative URL to redirect to when validation fails and required = true
* #param string $anchorParam Request parameter name which holds anchor name (#). Redirect to page fragment is not allowed according to HTTP protocol specification, but browsers do support it
* #throws Zend_Controller_Action_Exception if no referer is specified and $required == false or $checkdomain is true and domains do not match
*/
public function direct($required = true, $anchorParam = null, $validateDomain = true, $allowSubdomain = false, $alternative = null)
{
$front = Zend_Controller_Front::getInstance();
$request = $front->getRequest();
$referer = $request->getPost('http_referer');
if (empty($referer)) {
$referer = $request->getServer('HTTP_REFERER');
if (empty($referer)) {
$referer = $request->getParam('http_referer');
}
}
if (null === $alternative) {
$alternative = $request->getPost('http_referer');
if (null === $alternative) {
$alternative = $request->getParam('http_referer');
}
}
if ($referer) {
if ($validateDomain) {
if (!$this->validateDomain($referer, $allowSubdomain)) {
$this->_exception($alternative);
}
}
if (null != $anchorParam) {
$referer .= '#' . $request->getParam($anchorParam);
}
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl($referer);
} elseif($required) {
$this->_exception($alternative);
}
}
/**
* #throws Zend_Controller_Action_Exception With specified message
* #param string $message Exception message
* #param string $alternative
*/
private function _exception($alternative = null, $message = 'HTTP_REFERER is required.')
{
if ($alternative) {
if (Zend_Uri::check($alternative)) {
$redirector = new Zend_Controller_Action_Helper_Redirector();
$redirector->gotoUrl($alternative);
}
}
throw new Zend_Controller_Action_Exception($message);
}
/**
* Check if domain from current url and domain from specified url are the same
* #param string $url Target url
* #param string $allowSubdomain false
*/
public function validateDomain($url, $allowSubdomain = false)
{
if (!Zend_Uri::check($url)) {
return false;
}
$currentUri = $this->getCurrentUri();
$uri = Zend_Uri_Http::fromString($currentUri);
$currentDomain = $uri->getHost();
$uri = Zend_Uri_Http::fromString($url);
$target = $uri->getHost();
if ($allowSubdomain) {
// Find second dot from the end
$pos = strrpos($target, '.');
if (false !== $pos) {
$pos = strrpos(substr($target, 0, $pos), '.');
if (false !== $pos) {
$target = substr($target, $pos+1);
}
}
}
if ($target === $currentDomain) {
return true;
}
return false;
}
/**
* #return string Current URL
*/
public function getCurrentUri()
{
$request = $this->getRequest();
$path = $request->getRequestUri();
$server = $request->getServer();
$host = $request->getServer('HTTP_HOST');
$protocol = $request->getServer('SERVER_PROTOCOL');
if (!empty($protocol)) {
$protocol = explode('/', $protocol);
$protocol = strtolower($protocol[0]);
}
if (empty($protocol)) {
$protocol = 'http';
}
$baseUrl = $protocol . '://' . $host . '/';
$path = trim($path, '/\\');
$url = $baseUrl . $path;
return $url;
}
/**
* Like str_replace, but only once
* #param string $search
* #param string $replace
* #param string $subject
*/
public function replaceOnce($search, $replace, $subject)
{
$firstChar = strpos($subject, $search);
if($firstChar !== false) {
$beforeStr = substr($subject, 0, $firstChar);
$afterStr = substr($subject, $firstChar + strlen($search));
return $beforeStr . $replace . $afterStr;
} else {
return $subject;
}
}
}