Save values after redirect - php

I am saving values into $_SESSiON variable, but after I submit form, which redirect me to the same page, $_SESSION variable is empty.
include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth'])){
//Initialize google client
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
//Authentificate and return token
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}elseif(isset($_REQUEST['upload'])){
if(isset($_SESSION['auth']))
{
//Initialize google client
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], "https://www.googleapis.com/auth/drive");
}
//Here is undefined index 'token'
$_SESSION['auth']->setAccessToken($_SESSION['token']);
//Initialize new object for file transfer
new googleTransfer($_SESSION['auth']->getGoogleClient());
}
This is content of $_SESSION variable in elseif statement. Which makes me confused because there is only auth saved inside, which doesn't have anything set inside.
Array
(
[auth] => GoogleAuthorize Object
(
[client:GoogleAuthorize:private] => Google_Client Object
(
[auth:Google_Client:private] => Google\Auth\OAuth2 Object
(
[authorizationUri:Google\Auth\OAuth2:private] => GuzzleHttp\Psr7\Uri Object
(
[scheme:GuzzleHttp\Psr7\Uri:private] => https
[userInfo:GuzzleHttp\Psr7\Uri:private] =>
[host:GuzzleHttp\Psr7\Uri:private] => accounts.google.com
[port:GuzzleHttp\Psr7\Uri:private] =>
[path:GuzzleHttp\Psr7\Uri:private] => /o/oauth2/auth
[query:GuzzleHttp\Psr7\Uri:private] =>
[fragment:GuzzleHttp\Psr7\Uri:private] =>
)
[tokenCredentialUri:Google\Auth\OAuth2:private] => GuzzleHttp\Psr7\Uri Object
(
[scheme:GuzzleHttp\Psr7\Uri:private] => https
[userInfo:GuzzleHttp\Psr7\Uri:private] =>
[host:GuzzleHttp\Psr7\Uri:private] => www.googleapis.com
[port:GuzzleHttp\Psr7\Uri:private] =>
[path:GuzzleHttp\Psr7\Uri:private] => /oauth2/v4/token
[query:GuzzleHttp\Psr7\Uri:private] =>
[fragment:GuzzleHttp\Psr7\Uri:private] =>
)
[redirectUri:Google\Auth\OAuth2:private] => http://localhost:81/FileTransfer/src/testik.php?auth
[clientId:Google\Auth\OAuth2:private] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[clientSecret:Google\Auth\OAuth2:private] => Ab-DiaYYRnVSFf8JGay-TIMN
[username:Google\Auth\OAuth2:private] =>
[password:Google\Auth\OAuth2:private] =>
[scope:Google\Auth\OAuth2:private] =>
[state:Google\Auth\OAuth2:private] =>
[code:Google\Auth\OAuth2:private] =>
[issuer:Google\Auth\OAuth2:private] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[audience:Google\Auth\OAuth2:private] =>
[sub:Google\Auth\OAuth2:private] =>
[expiry:Google\Auth\OAuth2:private] => 3600
[signingKey:Google\Auth\OAuth2:private] =>
[signingAlgorithm:Google\Auth\OAuth2:private] =>
[refreshToken:Google\Auth\OAuth2:private] =>
[accessToken:Google\Auth\OAuth2:private] =>
[idToken:Google\Auth\OAuth2:private] =>
[expiresIn:Google\Auth\OAuth2:private] =>
[expiresAt:Google\Auth\OAuth2:private] =>
[issuedAt:Google\Auth\OAuth2:private] =>
[grantType:Google\Auth\OAuth2:private] =>
[extensionParams:Google\Auth\OAuth2:private] => Array
(
)
)
[http:Google_Client:private] =>
[cache:Google_Client:private] =>
[token:Google_Client:private] =>
[config:Google_Client:private] => Array
(
[application_name] =>
[base_path] => https://www.googleapis.com
[client_id] => 108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com
[client_secret] => Ab-DiaYYRnVSFf8JGay-TIMN
[redirect_uri] => http://localhost:81/FileTransfer/src/testik.php?auth
[state] =>
[developer_key] =>
[use_application_default_credentials] =>
[signing_key] =>
[signing_algorithm] =>
[subject] =>
[hd] =>
[prompt] =>
[openid.realm] =>
[include_granted_scopes] =>
[login_hint] =>
[request_visible_actions] =>
[access_type] => offline
[approval_prompt] => auto
[retry] => Array
(
)
[cache_config] => Array
(
)
[token_callback] =>
)
[logger:Google_Client:private] =>
[deferExecution:Google_Client:private] =>
[requestedScopes:protected] => Array
(
[0] => https://www.googleapis.com/auth/drive
)
)
[authUrl:GoogleAuthorize:private] =>
https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=offline&client_id=108715515230-g8e7tjh2d7luiggtfes6fsdv17n794hu.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A81%2FFileTransfer%2Fsrc%2Ftestik.php%3Fauth&state&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&approval_prompt=auto
[token:GoogleAuthorize:private] =>
)
)

include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth']) || isset($_REQUEST['upload'])){
if(!isset($_SESSION['auth']){
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
//Authentificate and return token
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}
if(isset($_REQUEST['upload'])){
new googleTransfer($_SESSION['auth']->getGoogleClient());
}
}

include 'googleauthorize.php';
include 'googleTransfer.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if (isset($_REQUEST['logout']))
unset($_SESSION['auth']);
if(isset($_REQUEST['auth'])){
// You have initialize the session variable auth here.
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?auth", "https://www.googleapis.com/auth/drive");
//Get authorize URL
$authUrl = $_SESSION['auth']->obtainAuthorizeUrl();
//Redirect
if(!isset($_GET['code'])){
$_SESSION['auth']->redirect($authUrl);
}
$_SESSION['token'] = $_SESSION['auth']->obtainAccessToken();
if(!isset($_SESSION['refreshToken']))
{
$_SESSION['refreshToken'] = $_SESSION['auth']->getRefreshToken();
//Call method to save token into DB
}
}elseif(isset($_REQUEST['upload'])){
// but how will it set here? when not having value? You have put the //session initialize here also.
$_SESSION['auth'] = new GoogleAuthorize(__DIR__ . '/../oauth-credentials.json', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], "https://www.googleapis.com/auth/drive");
if(isset($_SESSION['auth']))
{
$_SESSION['auth']->setAccessToken($_SESSION['token']);
}
//Initialize new object for file transfer
new googleTransfer($_SESSION['auth']->getGoogleClient());
}

Related

getting UNKNOWN_ENVELOPE_RECIPIENT docusign php API with template

I am working on the Docusign php rest API. Everything was working , But now i have to USe template with this . I wrote the script for this . But now i am getting this error .
Error Code:UNKNOWN_ENVELOPE_RECIPIENT Error Message : The recipient
you have identified is not a valid recipient of the specified
envelope.
But if i remove the ClientUserId
$viewrequest->setClientUserId('12345');
I am getting the error
Error Code:ACCOUNT_NOT_AUTHORIZED_FOR_ENVELOPE Error Message : This
account is not authorized to access the requested envelope.
Here is my function to create the docusign request.
include_once('DocuSign/bootstrap.php');
echo signatureRequestFromTemplate();
function signatureRequestFromTemplate()
{
$recipientEmail= "test#gmail.com";
$recipientName = "test";
$username = "testuser#gmail.com";
$password = "telemate";
$integrator_key = "SALE-252453454-54b3-4a86-bb25-1f21cb2edc21";
$documentFileName = __DIR__ ."/Contract.pdf";
$documentName = "datedDoc.txt";
$host = "https://demo.docusign.net/restapi";
// create configuration object and configure custom auth header
$config = new DocuSign\eSign\Configuration();
$config->setHost($host);
$config->addDefaultHeader("X-DocuSign-Authentication", "{\"Username\":\"" . $username . "\",\"Password\":\"" . $password . "\",\"IntegratorKey\":\"" . $integrator_key . "\"}");
// instantiate a new docusign api client
$apiClient = new DocuSign\eSign\ApiClient($config);
$accountId = null;
try
{
//*** STEP 1 - Login API: get first Account ID and baseURL
$authenticationApi = new DocuSign\eSign\Api\AuthenticationApi($apiClient);
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
$loginInformation = $authenticationApi->login($options);
if(isset($loginInformation) && count($loginInformation) > 0)
{
$loginAccount = $loginInformation->getLoginAccounts()[0];
$host = $loginAccount->getBaseUrl();
$host = explode("/v2",$host);
$host = $host[0];
// UPDATE configuration object
$config->setHost($host);
// instantiate a NEW docusign api client (that has the correct baseUrl/host)
$apiClient = new DocuSign\eSign\ApiClient($config);
if(isset($loginInformation))
{
$accountId = $loginAccount->getAccountId();
if(!empty($accountId))
{
//*** STEP 2 - Signature Request from a Template
// create envelope call is available in the EnvelopesApi
$envelopeApi = new DocuSign\eSign\Api\EnvelopesApi($apiClient);
// assign recipient to template role by setting name, email, and role name. Note that the
// template role name must match the placeholder role name saved in your account template.
$templateRole = new DocuSign\eSign\Model\TemplateRole();
$templateRole->setEmail($recipientEmail);
$templateRole->setName($recipientName);
$templateRole->setRoleName("Buyer");
// instantiate a new envelope object and configure settings
$envelop_definition = new DocuSign\eSign\Model\EnvelopeDefinition();
$envelop_definition->setEmailSubject("[DocuSign PHP SDK] - Signature Request Sample");
$envelop_definition->setTemplateId("EDAA30DE-551F-46C7-A7D3-9B6CA33AD07A");
$envelop_definition->setTemplateRoles(array($templateRole));
// set envelope status to "sent" to immediately send the signature request
$envelop_definition->setStatus("sent");
// optional envelope parameters
$options = new \DocuSign\eSign\Api\EnvelopesApi\CreateEnvelopeOptions();
$options->setCdseMode(null);
$options->setMergeRolesOnDraft(null);
// create and send the envelope (aka signature request)
$envelop_summary = $envelopeApi->createEnvelope($accountId, $envelop_definition, $options);
$document=json_decode($envelop_summary);
$envloped=$document->envelopeId;
$ReturnUrl="http://www.test.com/demo2/?action=docusign_request&uid=10&envelopid=" . $envloped;
$viewrequest = new DocuSign\eSign\Model\RecipientViewRequest();
$viewrequest->setUserName($recipientName);
$viewrequest->setEmail($recipientEmail);
//$viewrequest->setRecipientId(1);
//$viewrequest->setClientUserId('12345');
$viewrequest->setAuthenticationMethod('email');
$viewrequest->setReturnUrl($ReturnUrl);
$envelopview=$envelopeApi->createRecipientView($accountId,$document->envelopeId,$viewrequest);
echo $redirecturl=$envelopview->getUrl();
if(!empty($envelop_summary))
{
//echo "$envelop_summary";
}
}
}
}
}
catch (DocuSign\eSign\ApiException $ex)
{
echo "Exception: " . $ex->getMessage() . "\n";
}
}
I test it by using listRecipients it give me this response
DocuSign\eSign\Model\Recipients Object
(
[signers:protected] => Array
(
[0] => DocuSign\eSign\Model\Signer Object
(
[signature_info:protected] =>
[default_recipient:protected] =>
[tabs:protected] =>
[sign_in_each_location:protected] => false
[offline_attributes:protected] =>
[require_signer_certificate:protected] =>
[require_sign_on_paper:protected] =>
[can_sign_offline:protected] =>
[is_bulk_recipient:protected] => false
[bulk_recipients_uri:protected] =>
[recipient_supplies_tabs:protected] =>
[excluded_documents:protected] =>
[name:protected] => test
[email:protected] => test#gmail.com
[email_recipient_post_signing_url:protected] =>
[signing_group_id:protected] =>
[signing_group_name:protected] =>
[signing_group_users:protected] =>
[recipient_id:protected] => 1
[recipient_id_guid:protected] => e074bc90-44a0-4a0f-a9a6-68dd2ae3747c
[access_code:protected] =>
[add_access_code_to_email:protected] =>
[require_id_lookup:protected] => false
[id_check_configuration_name:protected] =>
[social_authentications:protected] =>
[phone_authentication:protected] =>
[saml_authentication:protected] =>
[sms_authentication:protected] =>
[user_id:protected] => a36eb466-1b84-47a4-9e0d-733d16637444
[client_user_id:protected] =>
[embedded_recipient_start_url:protected] =>
[custom_fields:protected] =>
[routing_order:protected] => 1
[id_check_information_input:protected] =>
[recipient_attachments:protected] =>
[note:protected] =>
[role_name:protected] => Buyer
[status:protected] => sent
[signed_date_time:protected] =>
[delivered_date_time:protected] =>
[declined_date_time:protected] =>
[sent_date_time:protected] =>
[declined_reason:protected] =>
[delivery_method:protected] =>
[fax_number:protected] =>
[template_locked:protected] =>
[template_required:protected] =>
[email_notification:protected] =>
[inherit_email_notification_configuration:protected] =>
[error_details:protected] =>
[recipient_authentication_status:protected] =>
[total_tab_count:protected] =>
)
)
[agents:protected] => Array
(
)
[editors:protected] => Array
(
)
[intermediaries:protected] => Array
(
)
[carbon_copies:protected] => Array
(
)
[certified_deliveries:protected] => Array
(
)
[in_person_signers:protected] => Array
(
)
[recipient_count:protected] => 1
[current_routing_order:protected] => 1
[error_details:protected] =>
)
I have solved this Errror . Actually i need to add ClientId in template setting also . I just added $templateRole->setClientUserId('12345');
$templateRole = new DocuSign\eSign\Model\TemplateRole();
$templateRole->setEmail($recipientEmail);
$templateRole->setName($recipientName);
$templateRole->setRoleName("Buyer");
$templateRole->setClientUserId('12345'); // added this

Magento 2.0 REST API Oauth error

The below php script is our rest api to retrieve customer info as admin
-The script is getting the admin login and authorize page correctly but after the authorize it is giving the error
OAuthException Object ( [message:protected] => Invalid auth/bad
request (got a 403, expected HTTP/1.1 20X or a redirect)
[string:Exception:private] => [code:protected] => 403 [file:protected]
=> /home/xxxx/public_html/oauth_admin.php [line:protected] => 39 [trace:Exception:private] => Array ( [0] => Array ( [file] =>
/home/xxxxx/public_html/oauth_admin.php [line] => 39 [function] =>
fetch [class] => OAuth [type] => -> [args] => Array ( [0] =>
http://www.xxxxx.com/api/rest/customers [1] => Array ( ) [2] => GET
[3] => Array ( [Content-Type] => application/xml [Accept] => / ) ) ) )
[previous:Exception:private] => [lastResponse] =>
{"messages":{"error":[{"code":403,"message":"Access denied"}]}}
[debugInfo] => Array ( [sbs] => xxxxx [body_recv] =>
{"messages":{"error":[{"code":403,"message":"Access denied"}]}} ) ))
I have tried every blog/post to try get this working and at this stage no doubt its something very obvious but I cant spot it...help greatly appreciated!
<?php
$callbackUrl = "http://www.site2.com/oauth_admin.php";
$temporaryCredentialsRequestUrl = "http://www.site1.com/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'https://www.site1.com/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://www.site1.com/oauth/token';
$apiUrl = 'http://www.site1.com/api/rest';
$consumerKey = 'xxxxx';
$consumerSecret = 'xxxxx';
session_start();
if (!isset($_GET['oauth_token']) && isset($_SESSION['state']) && $_SESSION['state'] == 1) {
$_SESSION['state'] = 0;
}
try {
$authType = ($_SESSION['state'] == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if ($_SESSION['state'] == 1) {
$oauthClient->setToken($_GET['oauth_token'], $_SESSION['secret']);
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken($_SESSION['token'], $_SESSION['secret']);
$resourceUrl = "$apiUrl/customers";
//$oauthClient->fetch($resourceUrl);
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/xml', 'Accept' => '*/*'));
$customers = json_decode($oauthClient->getLastResponse());
print_r($customers);
}
} catch (OAuthException $e) {
print_r($e);
}
Can't comment yet, but does the user have the correct roles? Had the same problem and it turned out to be a user that wasn't allowed to access parts of Magento.
Here's a link to the documentation of Magento which explains this: http://devdocs.magento.com/guides/m1x/api/rest/permission_settings/permission_settings.html
Also: go to System > Permissions and check if the user you use to connect to the api has the proper permissions.

Twitter Codebird Error

I am trying to use codebird to tweet using PHP. Initially I was unable to get Access Token but after I defined CallbackURL in settings that issue seems to be resolved. Now it is returning oauth token:
Codebird\Codebird Object ( [_oauth_token:protected] => codehere [_oauth_token_secret:protected] => codehere [_return_format:protected] => 0 [_supported_media_files:protected] => Array ( [0] => 1 [1] => 2 [2] => 3 ) [_version:protected] => 3.0.0-dev [_use_curl:protected] => 1 [_timeout:protected] => 10000 [_connectionTimeout:protected] => 3000 )
But when i try to tweet i get following error:
stdClass Object ( [errors] => Array ( [0] => stdClass Object ( [code]
=> 89 [message] => Invalid or expired token. ) ) [httpstatus] => 401 [rate] => )
Following is my code
Codebird\Codebird::setConsumerKey('copy+paste from twitter', 'copy+paste from twitter'); // I changed it to my settings
$cb = \Codebird\Codebird::getInstance();
if (! isset($_SESSION['oauth_token'])) {
// get the request token
$reply = $cb->oauth_requestToken(array(
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
));
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken(array(
'oauth_verifier' => $_GET['oauth_verifier']
));
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
print_r($cb);
$params = array(
'status' => 'Auto Post on Twitter with PHP http://goo.gl/OZHaQD #php #twitter'
);
$reply = $cb->statuses_update($params);
print_r($reply);
Thanks in advance for the assistance.
Is your callback address the one registered with Twitter in the app definition?
Do you have "read and write" access in the app definition?
Have you exceeded the rate limit for posting?
I'd check those things first, as I don't see anything obviously missing from your code snippet.

Problems implementing dropbox API into php

I am trying to create a page that will display the contents of a dropbox folder, in a presentable sandbox fashion, and allow the browsing user (who is logged into a website I have been developing) to be able to click and download the various files within the folders.
Here is the code I'm using:
This is the file bootstrap.php...
<?php
// Prevent calling this script directly
if ($_SERVER["SCRIPT_FILENAME"] == __FILE__) {
exit("Access denied!");
}
// app settings
$config = array();
$config["dropbox"]["app_key"] = "***";
$config["dropbox"]["app_secret"] = "***";
// ACCESS_TYPE should be "dropbox" or "app_folder"
$config["dropbox"]["access_type"] = "dropbox";
$config["app"]["root"] = ((!empty($_SERVER["HTTPS"])) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . "/";
$config["app"]["datadir"] = dirname(__FILE__) . "/data";
$config["app"]["authfile"] = $config["app"]["datadir"] . "/auth.php";
// turn on error reporting for development
error_reporting(E_ALL|E_STRICT);
ini_set("display_errors", true);
// environment check
if (!is_dir($config["app"]["datadir"]) || !is_writable($config["app"]["datadir"])) {
exit("The data directory is not writeable!");
}
if (file_exists($config["app"]["authfile"]) && !is_writable($config["app"]["authfile"])) {
exit("The auth storage file is not writeable!");
}
// Load libraries and start a new session
require_once "lib/dropbox/rest.php";
require_once "lib/dropbox/session.php";
require_once "lib/dropbox/client.php";
if(!isset($_SESSION)){session_start();}
// Search for a previously obtained access token
$access_token = null;
if (file_exists($config["app"]["authfile"])) {
include_once $config["app"]["authfile"];
}
This is the file authorize.php...
<?php
require_once "bootstrap.php";
if (isset($access_token)) {
header("Location: ./");
exit;
}
try {
// Start a new Dropbox session
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"]
);
// The user is redirected here by Dropbox after the authorization screen
if (!empty($_GET["oauth_token"]) && !empty($_GET["uid"])) {
$uid = $_GET["uid"];
$token = array(
"oauth_token" => $_GET["oauth_token"],
"oauth_token_secret" => ""
);
if (!empty($_SESSION["request_token"])) {
$token["oauth_token_secret"] = $_SESSION["request_token"]["oauth_token_secret"];
}
/**
* The access token is all you'll need for all future API requests on
* behalf of this user, so you should store it away for safe-keeping
* (even though we don't for this article). By storing the access
* token, you won't need to go through the authorization process again
* unless the user revokes access via the Dropbox website.
*/
if ($access_token = $session->obtainAccessToken($token)) {
parse_str($access_token, $token);
$access_token = $token;
unset($token);
// The output ov var_export is similar to:
// array("oauth_token_secret" => "aaaa", "oauth_token" => "bbbb", "uid" => "123456")
$data = '<?php $access_token = ' . var_export($access_token, true) . ";";
if (file_put_contents($config["app"]["authfile"], $data) === false) {
throw new Exception("Unable save access token");
}
// Authorized, redirect to index
//header("Location: index_inside.php");
echo "Authorized, click here to redirect!";
exit;
}
// The access token should be stored somewhere to be reused until
// it expires or is revoked by the user
}
else {
// We must start a new authorization cycle
if ($request_token = $session->obtainRequestToken()) {
// The request token must be subdivided in the two components
// oauth_token_secret and oauth_token and kept in the session
// because is needed in the next step
parse_str($request_token, $token);
$_SESSION["request_token"] = $token;
$url = $session->buildAuthorizeURL(
$token,
$config["app"]["root"] . basename($_SERVER["SCRIPT_NAME"]),
"en-US");
// Display or redirect to auth URL
echo '<p>Please visit Dropbox and authorize this application.</p>';
exit;
}
else {
throw new Exception("Unable to get request token");
}
}
}
catch (Exception $e) {
echo $e->getMessage();
}
This is the file list_inside.php...which is what is eventually included to present the list of folders (and ideally files with download links)...
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should be defined
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/Apps/Tools/";
// List contents of home directory
if ($home = $client->metadata($path)) {
echo "<p>Metadata content for <code>" . $path . "</code></p>";
echo "<pre>" . print_r($home, true) . "</pre>";
}
}
catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
Here is the output on the above code using metadata() :
Metadata content for /Apps/Tools/ Array (
[hash] => fa7f3577894553ffeb70ac0d96e49b99
[revision] => 71425
[rev] => 1170104ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools
[is_dir] => 1
[icon] => folder
[root] => dropbox
[contents] => Array
(
[0] => Array
(
[revision] => 71426
[rev] => 1170204ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Dry Creek Valley Cabernet Sauvignon
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[1] => Array
(
[revision] => 71436
[rev] => 1170c04ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Dry Creek Valley Sauvignon Blanc
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[2] => Array
(
[revision] => 71445
[rev] => 1171504ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Mendocino County Zinfandel
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
[3] => Array
(
[revision] => 71454
[rev] => 1171e04ef29f8
[thumb_exists] =>
[bytes] => 0
[modified] => Tue, 14 Jan 2014 03:10:05 +0000
[path] => /Apps/Tools/Burnside Road Pinot Noir California
[is_dir] => 1
[icon] => folder
[root] => dropbox
[size] => 0 bytes
)
)
[size] => 0 bytes )
I apologize for the choppy code, I am not extremely skilled at this, however, my friend needs help with the site, and I jumped in to help get dropbox working.
The problem is...It displays an array of information about the folders, but no files are visible with links for downloading.
Added info..here is another page code i try: (i list output for this directly below the php)
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should exist
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/webs.pdf";
$dest = $config["app"]["datadir"] . "/" . basename($path);
// Download a file
if ($file = $client->getFile($path, $dest)) {
if (!empty($dest)) {
unset($file["data"]);
echo "<p>File saved to: <code>" . $dest . "</code></p>";
echo "<pre>" . print_r($file, true) . "</pre>";
}
else {
header("Content-type: " . $file["mime"]);
echo $file["data"];
exit;
}
}
}
catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
Here is the output for the above code:
File saved to: /home/thisisyo/public_html/data/webs.pdf Array (
[name] => /home/thisisyo/public_html/data/webs.pdf
[mime] => application/pdf
[meta] => stdClass Object
(
[revision] => 35075
[rev] => 890304ef29f8
[thumb_exists] =>
[bytes] => 703289
[modified] => Thu, 20 Jun 2013 23:39:10 +0000
[client_mtime] => Wed, 20 Feb 2013 19:19:42 +0000
[path] => /webs.pdf
[is_dir] =>
[icon] => page_white_acrobat
[root] => dropbox
[mime_type] => application/pdf
[size] => 686.8 KB
)
)
Also, here is the class defined in client.php:
public function metadata($path, $list = true, $fileLimit = 10000, $hash = null, $revision = null, $includeDeleted = false) {
// Prepare argument list
$args = array(
"file_limit" => $fileLimit,
"hash" => $hash,
"list" => (int) $list,
"include_deleted" => (int) $includeDeleted,
"rev" => $revision
);
// Prepend the right access string to the desired path
if ("dropbox" == $this->accessType) {
$path = "dropbox" . $path;
}
else {
$path = "sandbox" . $path;
}
// Execute
$response = $this->Session->fetch("GET", $this->dropboxAPIURL, "/metadata/" . $path, $args);
return $response["body"];
}
This is the getFile() class define...
public function getFile($path, $outFile = null, $revision = null) {
$args = array();
if (!empty($revision)) {
$args["rev"] = $revision;
}
// Prepend the right access string to the desired path
if ("dropbox" == $this->accessType) {
$path = "dropbox" . $path;
}
else {
$path = "sandbox" . $path;
}
// Get the raw response body
$response = $this->Session->fetch("GET", $this->dropboxContentAPIURL, "/files/" . $path, $args, true);
if ($outFile != null) {
if (file_put_contents($outFile, $response["body"]) === false) {
throw new Exception("Unable to write file '$outfile'");
}
}
return array(
"name" => ($outFile) ? $outFile : basename($path),
"mime" => $response["headers"]["content-type"],
"meta" => json_decode($response["headers"]["x-dropbox-metadata"]),
"data" => $response["body"]
);
}
For your list_inside.php page, all you need to do is loop through your $client->metadata() array and print the HTML. Here's a sample for that page:
<?php
require_once "bootstrap.php";
if (!isset($access_token)) {
header("Location: authorize.php");
exit;
}
try {
// Start a new Dropbox session
// The access token should be defined
// The session should verify if the token is valid and throw an exception
$session = new DropboxSession(
$config["dropbox"]["app_key"],
$config["dropbox"]["app_secret"],
$config["dropbox"]["access_type"],
$access_token
);
$client = new DropboxClient($session);
$path = (!empty($_GET["path"])) ? $_GET["path"] : "/Apps/Tools/";
// List contents of home directory
if ($home = $client->metadata($path)) {
echo <<<EOF
<h1>Index of $index</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Last Modified</th>
<th>Size</th>
<th>Type</th>
</tr>
</thead>
<tbody>
EOF;
foreach($home as $list) {
$link = ($list[is_dir] == 1 ? "list_inside" : "download").".php?path=".$list[path];
$file = explode("/", $list[path]);
$path = $file[count($file)-1];
$size = ($list[bytes] == 0 ? "-" : $list[size]);
echo <<<EOF
<tr>
<td>$path</td>
<td>$list[modified]</td>
<td>$size</td>
<td>$list[type]</td>
</tr>
EOF;
}
echo <<<EOF
</tbody>
</table>
EOF;
}
} catch (Exception $e) {
echo "<strong>ERROR (" . $e->getCode() . ")</strong>: " . $e->getMessage();
if ($e->getCode() == 401) {
// Remove auth file
unlink($config["app"]["authfile"]);
// Re auth
echo '<p>Click Here to re-authenticate</p>';
}
}
?>
you just need to call a function to download the file .
require_once 'dropbox/DropboxClient.php';
$dropbox = new DropboxClient(array(
'app_key' => DROPBX_API_KEY,
'app_secret' => DROPBX_API_SECRET,
'app_full_access' => TRUE,
),'en');
$fileMetadata = $dropbox->DownloadFile($value->path,'download/'.$file);
check this if it can help you

facebook php api multiple users one computer force logout

I am working on an application that is basically going to operate in a Kiosk, the point is to allow users while they are at a business to be able to login to facebook and after logging in it posts a message saying they are there, afterwords they are given a coupon.
The problem has arisen that after they have logged in and then logged out, the next person logs in with their account ends up posting as the previous user, this continues adnauseum.
After getting their coupon the script automatically logs them out after 15 seconds and returns the application to the home screen for the next user. When they login, which they are able to do it returns them to the page asking for permission to post, but it is pulling all of the previous users information. This is the code being called in the page after being sent to logging in on facebook.
<?php
//include the Facebook PHP SDK
include_once 'couponGenerator/facebook.php';
//start the session if necessary
if( session_id() ) {
} else {
session_start();
}
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => '00000000000',
'secret' => '000000000000000000000',
'cookie' => true,
'status' => true,
'oath' => true
));
$access_token = $facebook->getAccessToken();
$_SESSION['active'][$access_token];
//get the news feed of the active page using the page's access token
$page_feed = $facebook->api(
'/me/feed',
'GET',
array(
'access_token' => $_SESSION['active']['access_token']
)
);
$fbuser = $facebook->api('/me');
//var_dump($page_feed); exit;
?>
I have attempted on the homepage of of deleting facebook cookies and sessions and this has not solved anything, I am just trying to figure out what I am doing wrong and any advice would be very welcome.
$facebook->destroySession();
$facebook->_killFacebookCookies();
public function _killFacebookCookies()
{
// get your api key
$apiKey = $this->getAppId();
// get name of the cookie
$cookie = $this->getSignedRequestCookieName();
$cookies = array('user', 'session_key', 'expires', 'ss');
foreach ($cookies as $name)
{
setcookie($apiKey . '_' . $name, false, time() - 3600);
unset($_COOKIE[$apiKey . '_' . $name]);
}
setcookie($apiKey, false, time() - 3600);
unset($_COOKIE[$apiKey]);
$this->clearAllPersistentData();
}
Here is the updated connection class
`
<?php
//include the Facebook PHP SDK
include_once 'facebook.php';
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => '122628977190080',
'secret' => '123123123123123123123123',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
unset ($_SESSION['active'][$access_token]);
session_unregister ($_SESSION['active'][$access_token]);
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//start the session if needed
if( session_id() ) {
} else {
session_start();
}
//do stuff when already logged in
//get the user's access token
$access_token = $facebook->getAccessToken();
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'email');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,email',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me/accounts',
'GET',
array(
'access_token' => $access_token
)
);
//save the information inside the session
$_SESSION['access_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
//save the first page as the default active page
$_SESSION['active'] = $accounts['data'][0];
//redirect to manage.php
header('Location: ../facebook_result.php');
} else {
//if not, let's redirect to the ALLOW page so we can get access
//Create a login URL using the Facebook library's getLoginUrl() method
$login_url_params = array(
'scope' => 'read_stream,email',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
//redirect to the login URL on facebook
header("Location: {$login_url}");
exit();
}
?>`
After calling the logoff script, I am run this piece of code on the homepage to see if everything is set.
<?php
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
echo "$uid";
} catch (FacebookApiException $e) {
print_r($e);
}
?>
it gives me this result
FacebookApiException Object ( [result:protected] =>
Array ( [error] => Array ( [message] =>
An active access token must be used to query information about the current user.
[type] => OAuthException [code] => 2500 ) )
[message:protected] => An active access token must be
used to query information about the current user.
[string:private] => [code:protected] => 0 [file:protected] =>
/home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php
[line:protected] => 1046 [trace:private] => Array ( [0] => Array ( [file] => /home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php [line] => 751 [function] => throwAPIException [class] => BaseFacebook [type] => -> [args] => Array ( [0] => Array ( [error] => Array ( [message] => An active access token must be used to query information about the current user. [type] => OAuthException [code] => 2500 ) ) ) ) [1] => Array ( [function] => _graph [class] => BaseFacebook [type] => -> [args] => Array ( [0] => /me ) ) [2] => Array ( [file] => /home/m3dev/public_html/couponsite/couponGenerator/base_facebook.php [line] => 560 [function] => call_user_func_array [args] => Array ( [0] => Array ( [0] => Facebook Object ( [appId:protected] => 162628977190080 [apiSecret:protected] => **SECRET KEY REMOVED ** [user:protected] => 0 [signedRequest:protected] => Array ( [algorithm] => HMAC-SHA256 [code] => 961628b1ca0354544541d58e.1-34319949|p3D3pSNoawlC1wBllhiN7zoEpJY [issued_at] => 1331218933 [user_id] => 34319949 ) [state:protected] => [accessToken:protected] => 162628977190080|**SECRET KEY REMOVED** [fileUploadSupport:protected] => ) [1] => _graph ) [1] => Array ( [0] => /me ) ) ) [3] => Array ( [file] => /home/m3dev/public_html/couponsite/index.php [line] => 71 [function] => api [class] => BaseFacebook [type] => -> [args] => Array ( [0] => /me ) ) ) )
You may be destroying a Facebook session but you don't seem to be destroying your own session.
Clear out
$_SESSION['active'][$access_token];
You need to force Facebook Re-Authentication for each user.
I'm not sure if the PHP API you're using supports this, but the OAuth dialog can receive a auth_type that when valued to reauthenticate forces the user to provide his credentials:
$dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. '&auth_type=reauthenticate&auth_nonce=' . $auth_nonce;
This can be done useg the Javascript API as well.

Categories