Twitter OAuth Showing Timeline Not Tweets - twitter

Anyone know how I can tweak the settings in the Wordpress theme used in this site (http://www.ethnecity.church.ly/) to make the Twitter section (near the bottom left of the page) show the tweets for the account instead of the timeline from the Twitter account? Note: the plugin is using OAuth...I just don't know how to tell it to display tweets instead of the timeline.
I believe this is the code that displays the twitter info:
<?php
$user_screen_name = 'ethnecity';
$user_full_name = '(removed)';
$settings = array(
'consumer_key' => '(removed)',
'consumer_secret' => '(removed)',
'access_token' => '(removed)',
'access_token_secret' => '(removed)');
$api_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
$api_params = array(
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false');
// OAuth:
function oauth_encode($data){
if(is_array($data)){
return array_map('oauth_encode', $data);
} else if(is_scalar($data)) {
return str_ireplace(array('+', '%7E'), array(' ', '~'), rawurlencode($data));
} else {
return '';
}}
// OAuth base settings
$oauth_params = array(
'oauth_consumer_key' => $settings['consumer_key'],
'oauth_nonce' => md5(microtime() . mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => $settings['access_token'],
'oauth_version' => '1.0',
);
// Sign OAuth params
$sign_params = array_merge($oauth_params, $api_params);
uksort($sign_params, 'strcmp');
foreach ($sign_params as $k => $v) {
$sparam[] = oauth_encode($k) . '=' . oauth_encode($v);
}
$sparams = implode('&', $sparam);
$base_string = 'GET&' . oauth_encode($api_url) . '&' . oauth_encode($sparams);
$signing_key = oauth_encode($settings['consumer_secret']) . '&' . oauth_encode($settings['access_token_secret']);
$oauth_params['oauth_signature'] = oauth_encode(base64_encode(hash_hmac('sha1', $base_string, $signing_key, TRUE)));
// Set Authorization header:
uksort($oauth_params, 'strcmp');
foreach ($oauth_params as $k => $v) {
$hparam[] = $k . '="' . $v . '"';
}
$hparams = implode(', ', $hparam);
$headers = array();
$headers['Expect'] = '';
$headers['Authorization'] = 'OAuth ' . $hparams;
foreach ($headers as $k => $v) {
$curlheaders[] = trim($k . ': ' . $v);
}
// Format params:
foreach ($api_params as $k => $v) {
$rparam[] = $k . '=' . $v;
}
$rparams = implode('&', $rparam);
// echo "curl --get '" . $api_url . "' --data '" . $rparams . "' --header 'Authorization: OAuth " . $hparams . "' --verbose" . PHP_EOL;
// GET:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url . '?' . $rparams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlheaders);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$info = curl_getinfo($ch);
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);
function get_twitterfeeds(){
global $code; global $response;
if($code != 200){
//echo 'Error' . PHP_EOL;
//echo $code . PHP_EOL;
//print_r($response);
//print_r($info);
} else {
$all = json_decode($response, true);
//echo '<pre />';
// print_r($all);
//exit;
return $all;
}
}
?>

Your code should be modified so as to retrieve user's timeline. As per the current code it should return only tweets present on your timeline.
If you need only your's or a particular user's feed , your code should be modified in such a way that resource URL should be changed.
$api_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$api_params = array(
'screen_name' => 'ethnecity'
'count' => 40,
'contributor_details' => 'false',
'include_entities' => 'false'
);
Please verify the document https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline

Related

Uploading videos by other people on your channel via site

I want users to send their videos on my YT channel via my site.
It worked last year but now Youtube requests users to be authenticated on Youtube.
If it even possible now?
Here is the code:
public function getPostParams()
{
$header = array(
"alg" => "RS256",
"typ" => "JWT"
);
$jwt = array(
"iss" => "gulliapp#appspot.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/youtube",
"aud" => "https://accounts.google.com/o/oauth2/token",
"exp" => time() + 3600,
"iat" => time()
);
$jwt_string = JWT::encode($jwt, null, 'RS256', "52e47342c1d175e88a94e0076e7a87474013a798", $header);
$headers = array(
"Content-type: application/x-www-form-urlencoded",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://accounts.google.com/o/oauth2/token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
curl_setopt($ch, CURLOPT_POST, true);
$post = "grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=" . $jwt_string ;
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$res = curl_exec($ch);
$url = curl_getinfo($ch);
$token = json_decode($res);
curl_close($ch);
return $token->access_token;
}
public function saveFile($file, $name, $description, $token)
{
$client = new Google_Client();
$client->setClientId(self::$OAUTH2_CLIENT_ID);
$client->setClientSecret(self::$OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://gulli.ru/videocontest/add/', FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$client->setAccessToken($token);
$client->setAccessType("offline");
$youtube = new Google_Service_YouTube($client);
if ($client->getAccessToken()) {
try{
$videoPath = $file['tmp_name'];
$snippet = new Google_Service_YouTube_VideoSnippet();
$snippet->setTitle("web2016");
$snippet->setDescription("web2016");
$snippet->setTags(array("tag1", "tag2"));
$snippet->setCategoryId("22");
$status = new Google_Service_YouTube_VideoStatus();
$status->privacyStatus = "private";
// Associate the snippet and status objects with a new video resource.
$video = new Google_Service_YouTube_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$insertRequest = $youtube->videos->insert("status,snippet", $video);
$media = new Google_Http_MediaFileUpload(
$client,
$insertRequest,
'video/*',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($videoPath));
$status = false;
$handle = fopen($videoPath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
fclose($handle);
$client->setDefer(false);
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
}
return false;
}

Retrieveng data from Google Webmasters Tools in PHP using Oauth 2.0

Hel-lo! Need to retrieve GWT data (top pages, top queries, internal/external links, etc.). Wrote a php-script (based on this):
//"GetAccessCode.php" file
$OAuth = array(
'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
'client_id' => 'here is my client id',
'client_secret' => 'here is my client secret',
'redirect_uri' => 'http://localhost/google/GetAccessCode.php',
'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token',
);
$token = array(
'access_token' => '',
'token_type' => '',
'expires_in' => '',
'refresh_token' => ''
);
$title = 'No Code';
$AuthCode = 'Null';
// see if error parameter exisits
$error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
if ($error != NULL)
{ // this means the user denied api access to GWMTs
$title = $error;
}
else
{ // does the code parameter exist?
$AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
if ($AuthCode == NULL)
{ // get authorization code
$OAuth_request = _formatOAuthReq($OAuth, "https://www.google.com/webmasters/tools/feeds/sites/"); //**WHAT URI NEED TO BE HERE?**
header('Location: ' . $OAuth_request);
exit; // the redirect will come back to this page and $code will have a value
}
else
{
$title = 'Got Authorization Code';
// now exchange Authorization code for access token and refresh token
$token_response = _get_auth_token($OAuth, $AuthCode);
$json_obj = json_decode($token_response);
$token['access_token'] = $json_obj->access_token;
$token['token_type'] = $json_obj->token_type;
$token['expires_in'] = $json_obj->expires_in;
$token['refresh_token'] = $json_obj->refresh_token;
$sites = _get_wmt_sites_feed($token);
echo $sites;
}
}
// Return the list of sites registered in your Google Webmaster Tools
function _get_wmt_sites_feed($access_tokens)
{
$post_string = "https://www.google.com/webmasters/tools/feeds/sites/"; //**WHAT URI NEED TO BE HERE?**
$post_string .= '?v=2';
$post_string .= '&oauth_token=' . $access_tokens['access_token'];
$response = file_get_contents($post_string);
return _parse_wmt_sites_response($response);
}
function _parse_wmt_sites_response($response)
{
$xml = simplexml_load_string($response);
$response = '<br />';
foreach ($xml->entry as $entry)
{
foreach ($entry->title as $title)
{
$response .= "<p>$title</p>";
}
}
return $response;
}
function _get_auth_token($params, $code)
{
$url = $params['oauth_token_uri'];
$fields = array(
'code' => $code,
'client_id' => $params['client_id'],
'client_secret' => $params['client_secret'],
'redirect_uri' => $params['redirect_uri'],
'grant_type' => 'authorization_code'
);
$response = _do_post($url, $fields);
return $response;
}
function _do_post($url, $fields)
{
$fields_string = '';
foreach ($fields as $key => $value)
{
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function _formatOAuthReq($OAuthParams, $scope)
{
$uri = $OAuthParams['oauth_uri'];
$uri .= "?client_id=" . $OAuthParams['client_id'];
$uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
$uri .= "&scope=" . $scope;
$uri .= "&response_type=code";
return $uri;
}
function _get_url_param($url, $name)
{
parse_str(parse_url($url, PHP_URL_QUERY), $params);
return isset($params[$name]) ? $params[$name] : null;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?= $title; ?></title>
</head>
<body>
<h1>OAuth2 Authorization Code</h1>
<p>Authorization Code: <?= $AuthCode; ?></p>
<p>access token: <?=$token['access_token'];?></p>
<p>expires in: <?=$token['expires_in'];?></p>
<p>refresh token: <?=$token['refresh_token'];?></p>
<p></p>
</body>
</html>
What URI need I to write in the code above instead of https:// www.google.com/webmasters/tools/feeds/sites/ to retrieve the desired data? In this nice code - https://github.com/eyecatchup/php-webmaster-tools-downloads - author uses https:// www.google.com/webmasters/tools/downloads-list?hl=en&siteUrl=http: //site.com/, but also he uses ClientLogin. I try to use this link in my script, but it generates mistakes, because, as I understand, this is not a right scope. So, what is right?
Also found this post here, it mentions about some Basic Authentication. I'm a beginner in Google API, please, tell, what do they mean?

Android & Apple Push Notifcations

I have an app set for push notification. The Android code works fine and I receive a push notification. For Apple, the phone just vibrates and makes sound for push notifications, but I don't get a badge or anything else.
Can someone please show me where I am going wrong?
<?php
// function to send Android push notification
function send_message($deviceToken, $message){
$messageArr['message'] = "";
if($message=="")
{
$messageArr['message'] = "Test data";
}
else
{
$messageArr['message'] = $message ;
}
$registatoin_ids = $deviceToken;
return mer_send_notification($registatoin_ids, $messageArr);
}
function mer_curlPost($url, $headers, $fields) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
function mer_send_notification($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$apiKey = 'mykeyishere';
echo 'Test if 4\n';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
$result = mer_curlPost($url, $headers, $fields);
return $result;
}
function sendNotification($dataArr, $device_token_array) {
$apns_url = NULL;
$apns_cert = NULL;
$apns_port = 2195;
$development = false;
if ($development) {
$apns_url = 'gateway.sandbox.push.apple.com';
$apns_cert = 'devcert.pem';
} else {
$apns_url = 'gateway.push.apple.com';
$apns_cert = 'prodcert.pem';
}
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
stream_context_set_option($stream_context, 'ssl', 'passphrase', 'mypassphrase');
$payload = array();
$payload['aps'] = $dataArr;
$payloadJson = json_encode($payload);
$apns = #stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT, $stream_context);
foreach ($device_token_array as $key => $device_token) {
$apns_message = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payloadJson)) . $payloadJson;
$xxx[] = #fwrite($apns, $apns_message);
}
$yyy = #socket_close($apns);
$zzz = #fclose($apns);
$arr = array();
$arr[] = $stream_context;
$arr[] = $apns;
$arr[] = $xxx;
$arr[] = $yyy;
$arr[] = $zzz;
return $arr;
}
The notification format for iOS is different than for Android. See here for iOS format: https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW1

How do I upload a file to sharepoint with the office365 rest api?

Im using following ruby code to upload files to office 365
uri = URI.parse("#{site_url}/_api/v1.0/me/files/#{folder}/children/#{temp_file.original_filename}/content")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Put.new(uri.path, initheader = {
'Content-Type' =>'application/octet-stream',
'Authorization' => 'Bearer ' + #current_user.o_auth_token,
'resource' => 'site_url'
})
req.set_form_data(
'file' => temp_file.read,
'Content-Type' => 'application/octet-stream'
)
JSON.parse(https.request(req).body)
The file uploaded to office 365 is corrupt. What's the issue in the code?
The following code in PHP works fine. Please note these are functions within a class and also requires creating a SharepointException class.
public function upload_file($folder_id, $filepath, $filename) {
//remove illegal characters form filename
try {
$filename = $this->clean_filename($filename);
} catch (SharepointException $e) {
throw new SharepointException($e->getMessage());
}
//build uri
if (is_null($folder_id)) {
$uri = $this->base_url . 'files/root/children/'.rawurlencode($filename).'/content?nameConflict=abort';
} else {
$uri = $this->base_url . 'files/'.$folder_id.'/children/'.rawurlencode($filename).'/content?nameConflict=abort';
}
$response = $this->upload($uri, $filepath);
if (array_key_exists('error', $response)) {
throw new SharepointException($response['error']);
}
return $response;
}
private function upload($uri, $filepath) {
$pointer = fopen($filepath, 'r+');
$stat = fstat($pointer);
$pointersize = $stat['size'];
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $pointer);
curl_setopt($ch, CURLOPT_INFILESIZE, (int)$pointersize);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
//Expect:
//HTTP response code 100 workaround
//see http://www.php.net/manual/en/function.curl-setopt.php#82418
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Expect:',
'Content-Type: application/json',
'Authorization: Bearer ' . $this->access_token,
));
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$accepted_codes = array(
'200',
'201',
);
if (!in_array($httpcode, $accepted_codes)) {
//generic error
$error = 'HTTP status code not expected - got '.$httpcode;
//more descriptive error
if ($httpcode == '400') {
$data = json_decode($response, true);
if (isset($data['error']['message'])) {
$error = $data['error']['message'];
}
}
return array('error' => $error);
}
return json_decode($response, true);
}
private function clean_filename($filename) {
$filename = preg_replace('/[*><|}{&#%~:"?\/\\\\]/', '', $filename);
if (strpos('.', $filename) === 0) {
$filename = substr($filename, 1);
}
if (empty($filename)) {
throw new SharepointException('File is empty after removing illegal characters.');
}
return $filename;
}

paypal access oauth login json_decode returned null

i have 2 PHP files, one index.php and the other one paypal.php.
The code for paypal.php is:
<?php
session_start();
$client_id = 'xxxxxxxxxxxx';
$client_secret = 'xxxxxxxxxxxxxxxxxxxx';
$scopes = 'email profile';
$app_return_url = 'http://xxx.com/xxx/paypal.php';
$nonce = time() . rand();
$code = $_REQUEST["code"];
if(empty($code)) {
$_SESSION['state'] = md5(uniqid(rand(), TRUE));
$paypal_auth_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?"
."client_id=".$client_id
."&response_type=code"
."&scope=".$scopes
."&nonce=".$nonce
."&state=".$_SESSION['state']
."&redirect_uri=".urlencode($app_return_url);
header("Location: $paypal_auth_url");
}else{
$token_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/tokenservice";
$postvals = "client_id=".$client_id
."&client_secret=".$client_secret
."&grant_type=authorization_code"
."&code=".$code;
$ch = curl_init($token_url);
$options = array(
CURLOPT_POST => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_POSTFIELDS => $postvals,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$atoken = json_decode($response);
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?"
."schema=openid"
."access_token=".$atoken->access_token;
$ch = curl_init($profile_url);
$options = array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_SSLVERSION => 3
);
curl_setopt_array( $ch, $options );
$response = curl_exec($ch);
curl_close($ch);
$profile= json_decode($response,true);
$_SESSION['paypal_user'] = "true";
$_SESSION['profile'] = $profile;
echo("<script> top.location.href='index.php'</script>");
}
?>
The code for index.php is:
<?php
session_start();
// LOGOUT
if ($_GET['logout'] == 'true'){
$_SESSION['paypal_user']="";
}
if (strlen($_SESSION['paypal_user'])){
// LOGGED USER
echo "<pre>";
print_r($_SESSION['profile']);
echo "</pre>";
echo "<br><BR> <a href='?logout=true'>LOGOUT</a>";
}else{
// LOGIN
?>
<a href='paypal.php' title='Paypal oAuth Login'>
<img src='https://www.paypalobjects.com/en_US/Marketing/i/btn/login-with-paypal-button.png'>
</a>
<?
}
?>
Any ideas why this code is not working? I tried var_dump json_decode and it returns null.
Thank you!
I may be wrong, but I believe you scopes need to be...
"scopes": "email https://uri.paypal.com/services/paypalattributes",
The URL is the profile
simply add '&' on before access token,he missed & symbol between two variables
$profile_url = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/userinfo?" ."schema=openid" ."**&**access_token=".$atoken->access_token;

Resources