I am trying to use Twitter API 1.1 with symfony2 and twig. So far I have succeed to pass all tweets as an array to the template but I am unable to get the latest tweet ONLY.
Everything works ok except the number or posts, so I am posting full code to help others also.
twitter functions
public function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
public function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
public function twitter_latest(){
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "***";
$oauth_access_token_secret = "***";
$consumer_key = "***";
$consumer_secret = "***";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = $this->buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make Requests
$header = array($this->buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
return $twitter_data;
}
Controller:
/**
* Index page
*
*/
public function indexAction()
{
$twitters = $this->twitter_latest();
return $this->render('mwwqTestBundle:Main:index.html.twig', array("twitters" => $twitters));
}
Twig template:
<div id="mainTwitter">
<ul id="twitter_update_list">
{% for twitter in twitters %}
{{ twitter.text }}
{% endfor %}
</ul>
</div>
{{ twitter.text[0] }}, {{ twitter[0].text }}, {{ twitter.text.[0] }} are not working
Why do you need to pass more than one tweet to the view if you only want to display one?
You could do something like this:
{% if loop.first %}
{{ twitter.text }}
{% endif %}
To change the count in the controller:
Presumably you were just trying to change the url variable directly. I think you need to do something like the following. Sure I've seen it somewhere but can't find the original author:
public function twitter_latest($count = 1){
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "***";
$oauth_access_token_secret = "***";
$consumer_key = "***";
$consumer_secret = "***";
$oauth = array( 'count' => $count,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = $this->buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make Requests
$header = array($this->buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '&count=' . $count,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
return $twitter_data;
}
{% for twi in tweet|slice(0, 2)%}
<li>
<div>{{twi.text}}</div>
<small><strong>{{twi.created_at|date("m/d/Y")}}</strong></small>
</li>
{% endfor %}
Related
i'm try to write dailymotion api upload php code
i'm use example code from https://developer.dailymotion.com/guides
it's work great
and i want add Geoblocking only allow Japan
this is my code
require_once 'Dailymotion.php';
// Account settings
$apiKey = 'xxxxxxxxxxxxxxxxxx';
$apiSecret = 'xxxxxxxxxxxxxxxxxx';
$testUser = 'xxxxxxxxxxxxxxxxxx#xxxx.com';
$testPassword = 'xxxxxxxxxxxxxxxxxx';
$videoTestFile = 'C:/output.mp4';
// Scopes you need to run your tests
$scopes = array(
'userinfo',
'feed',
'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(
Dailymotion::GRANT_TYPE_PASSWORD,
$apiKey,
$apiSecret,
$scopes,
array(
'username' => $testUser,
'password' => $testPassword,
)
);
$url = $api->uploadFile($videoTestFile);
$result = $api->post(
'/videos',
array(
'url' => $url,
'title' => 'Dailymotion PHP SDK upload test 2',
'tags' => 'dailymotion,api,sdk,test',
'channel' => 'videogames',
'published' => true,
'geoblocking' => 'JP', // i'm add this line
)
);
var_dump($result);
but i got this error
Fatal error: Uncaught exception 'DailymotionAuthRequiredException' with message 'Insufficient rights for the `geoblocking' parameter of route `POST /videos'. Required scopes: manage_videos'
anyone can tell me
what i'm doing wrong and help me fix this problem
thank you
'geoblocking' => 'JP'
change to 'geoblocking' => 'jp'
your code will be
require_once 'Dailymotion.php';
// Account settings
$apiKey = 'xxxxxxxxxxxxxxxxxx';
$apiSecret = 'xxxxxxxxxxxxxxxxxx';
$testUser = 'xxxxxxxxxxxxxxxxxx#xxxx.com';
$testPassword = 'xxxxxxxxxxxxxxxxxx';
$videoTestFile = 'C:/output.mp4';
// Scopes you need to run your tests
$scopes = array(
'userinfo',
'feed',
'manage_videos',
);
// Dailymotion object instanciation
$api = new Dailymotion();
$api->setGrantType(
Dailymotion::GRANT_TYPE_PASSWORD,
$apiKey,
$apiSecret,
$scopes,
array(
'username' => $testUser,
'password' => $testPassword,
)
);
$url = $api->uploadFile($videoTestFile);
$result = $api->post(
'/videos',
array(
'url' => $url,
'title' => 'Dailymotion PHP SDK upload test 2',
'tags' => 'dailymotion,api,sdk,test',
'channel' => 'videogames',
'published' => true,
'geoblocking' => 'jp' // NO , in last line
)
);
var_dump($result);
What I like to do is creating a full url.
Controller = 'A'
Action = 'doSomething'
param1 = $id
param2 = $id2
What I currently get is:
mydomain.com/A/doSomething?param1=X¶m2=XX
What I want is:
mydomain.com/A/doSomething/X/XX
Code:
$message = 'Test: '. Router::url([
"controller" => "A",
"action" => "doSomthing",
"param1" => $id,
"param2" => $id2,
'_full' => true
]);
$id1 = 'id1';
$id2 = 'id2';
$url= Router::url([
"controller" => "A",
"action" => "doSomething",
$id1,
$id2,
'_full' => true
]);
debug($url);
Outputs:
'http://host/a/do-something/id1/id2'
Try:
public function doSomthing($param1, $param2)
{
#your code here
}
I am trying to get a request token from Bitbucket but I'm getting "BAD REQUEST - Could not verify OAuth request". I am doing this with drupal and here is the code I have so far:
$key = "MY_KEY";
$secret ="MY_SECRET";
$timestamp = time();
$nonce = (int) (rand() * 100000000);
$callback = 'http://www.google.com'; //'htt//url('<front>', array('absolute' => TRUE)); //DRUPAL_ROOT . "/toolkittens/git";
$url = "https://bitbucket.org/api/1.0/oauth/request_token";
$data = array(
'oauth_nonce' => $nonce,
'oauth_timestamp' => $timestamp,
'oauth_consumer_key' => $key,
'oauth_signature_method' => 'PLAINTEXT',
'oauth_signature' => 'thisismysig',
'oauth_callback' => $callback,
'oauth_version' => '1.0',
);
$options = array(
'method' => 'POST',
'data' => drupal_http_build_query($data),
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
return drupal_http_request($url, $options);
You are providing a PLAINTEXT signature.
If you are requesting a token with the provided signature not encrypted, change your oauth_signature_method to 'PLAINTEXT', so bitbucket knows you didn't encrypt it.
$key = "MY_KEY";
$signature = "MY_SIGNATURE"; //I think this is your secret from bitbucket
$timestamp = time();
$nonce = rand();
$callback = DRUPAL_ROOT . "/toolkittens/git";
$url = "https://bitbucket.org/api/1.0/oauth/request_token";
$data = array(
'oauth_nonce' => $nonce,
'oauth_timestamp' => $timestamp,
'oauth_consumer_key' => $key,
'oauth_signature_method' => 'PLAINTEXT',
'oauth_signature' => $signature,
'oauth_callback' => $callback,
'oauth_version' => '1.0',
);
$options = array(
'method' => 'POST',
'data' => $data,
'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);
$full_url = url($url, array('query' => $data));
return drupal_http_request($full_url);
Also, you defined your options but never used them.
I cant pass the ID from the view (or from somewhere else). This is the url:
http://zend2.com/users/user-manager/edit/6
The controller :
public function editAction()
{
if ($this->request->isPost()) {
$post = $this->request->getPost();
echo $post->user_id; exit;
$userTable = $this->getServiceLocator()->get('UserTable');
$user = $userTable->getUser($post->id);
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$form->setData($post);
$this->getServiceLocator()->get('UserTable')->saveUser($user);
}
$userTable = $this->getServiceLocator()->get('UserTable');
$user = $userTable->getUser($this->params()->fromRoute('id'));
$form = $this->getServiceLocator()->get('UserEditForm');
$form->bind($user);
$viewModel = new ViewModel(array(
'form' => $form,
'user_id' => $this->params()->fromRoute('id')
));
return $viewModel;
}
And the view:
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'users_manager', 'action' => 'edit')));
$form->setAttribute('method', 'post');
What is the proper way to pass the ID ? I know that i dont pass the ID in the view but i am not even sure that this is right.
I solved it.
$form->setAttribute('action', $this->url(NULL,
array('controller' => 'users_manager', 'action' => 'edit'),null, true));
The 4th parameter for $this->url is "$reuseMatchedParameters", it speaks for itself.
An alternative is :
$options = ['Query' => ['id' => 12]];
echo $this->url('controller' => 'users_manager', 'action' => 'edit', $options);
I would like to set a query parameter when redirecting. I tried this:
$this->redirect()->toRoute('login/default', array('action' => 'forgotPassword', 'foo' => 'bar'));
It redirects to:
/login/forgotPassword
Instead of where I would like to redirect which is:
/login/forgotPassword?foo=bar
The query parameter belongs to the third parameter of the URL-Methods.
$this->redirect()->toRoute(
'login/default',
array(
'action' => 'forgotPassword'
),
array( 'query' => array(
'foo' => 'bar'
))
)
Plus.
To redirect a "access" or login, form you can use:
if (!$controller->identity()) {
$sm = $controller->getServiceLocator();
$router = $sm->get('router');
$request = $sm->get('request');
$routeMatch = $router->match($request);
$controller->redirect()->toRoute('login', array(),
array( 'query' =>
array('redir' => $routeMatch->getMatchedRouteName() ) ) );
}
Urls will be:
/login/?redir=current-route