8000 Add documentation in readme, make OAuth consumer key and secret static · codezninja/codebird-php@db24d9f · GitHub
[go: up one dir, main page]

Skip to content

Commit db24d9f

Browse files
committed
Add documentation in readme, make OAuth consumer key and secret static
1 parent 973c25e commit db24d9f

File tree

2 files changed

+263
-28
lines changed

2 files changed

+263
-28
lines changed

README.md

Lines changed: 160 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
codebird-php
22
============
3-
A simple wrapper for the Twitter API
3+
*A simple wrapper for the Twitter API*
44

55
Copyright (C) 2010-2012 J.M. <me@mynetx.net>
66

@@ -21,3 +21,162 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
2121
This is the PHP version of the Codebird library.
2222
It was forked from the JScript version.
2323
Please enable the CURL and OPENSSL extensions in your PHP environment.
24+
25+
Usage example
26+
-------------
27+
28+
```php
29+
require_once ('codebird.php');
30+
Codebird::setConsumerKey('YOURKEY', 'YOURSECRET'); // static, see 'Using multiple Codebird instances'
31+
32+
$cb = Codebird::getInstance();
33+
```
34+
35+
You may either set the OAuth token and secret, if you already have them:
36+
```php
37+
$cb->setToken('YOURTOKEN', 'YOURSECRET');
38+
```
39+
40+
Or you authenticate, like this:
41+
42+
```php
43+
session_start();
44+
45+
if (! isset($_GET['oauth_verifier'])) {
46+
// gets a request token
47+
$reply = $cb->oauth_requestToken(array(
48+
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
49+
));
50+
51+
// stores it
52+
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
53+
$_SESSION['oauth_token'] = $reply->oauth_token;
54+
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
55+
56+
// gets the authorize screen URL
57+
$auth_url = $cb->oauth_authorize();
58+
header('Location: ' . $auth_url);
59+
die();
60+
61+
} else {
62+
// gets the access token
63+
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
64+
$reply = $cb->oauth_accessToken(array(
65+
'oauth_verifier' => $_GET['oauth_verifier']
66+
));
67+
$_SESSION['oauth_token'] = $reply->oauth_token;
68+
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
69+
}
70+
```
71+
72+
When you have an access token, calling the API is simple:
73+
74+
```php
75+
$reply = (array) $cb->statuses_homeTimeline();
76+
print_r($reply);
77+
```
78+
79+
Tweeting is as easy as this:
80+
81+
```php
82+
$reply = $cb->statuses_update('status=Whohoo, I just tweeted!');
83+
```
84+
85+
For more complex parameters (see the [Twitter API documentation](https://dev.twitter.com/)),
86+
giving all parameters in an array is supported, too:
87+
88+
```php
89+
$params = array(
90+
'screen_name' => 'mynetx'
91+
);
92+
$reply = $cb->users_show($params);
93+
```
94+
95+
When uploading files to Twitter, the array syntax is obligatory:
96+
97+
```php
98+
$params = array(
99+
'status' => 'Look at this crazy cat! #lolcats',
100+
'media[]' => '/home/mynetx/lolcats.jpg'
101+
);
102+
$reply = $cb->statuses_updateWithMedia($params);
103+
```
104+
105+
Mapping API methods to Codebird function calls
106+
----------------------------------------------
107+
108+
As you can see from the last example, there is a general way how Twitter’s API methods
109+
map to Codebird function calls. The general rules are:
110+
111+
1. For each slash in a Twitter API method, use an underscore in the Codebird function.
112+
113+
Example: ```statuses/update``` maps to ```Codebird::statuses_update()```.
114+
115+
2. For each underscore in a Twitter API method, use camelCase in the Codebird function.
116+
117+
Example: ```statuses/home_timeline``` maps to ```Codebird::statuses_homeTimeline()```.
118+
119+
3. For each parameter template in method, use UPPERCASE in the Codebird function.
120+
Also don’t forget to include the parameter in your parameter list.
121+
122+
Example: ```statuses/show/:id``` maps to ```Codebird::statuses_show_ID('id=12345')```.
123+
124+
HTTP methods (GET, POST, DELETE etc.)
125+
-------------------------------------
126+
127+
Never care about which HTTP method (verb) to use when calling a Twitter API.
128+
Codebird is intelligent enough to fin F438 d out on its own.
129+
130+
Response codes
131+
--------------
132+
133+
The HTTP response code that the API gave is included in any return values.
134+
You can find it within the return object’s ```httpstatus``` property.
135+
136+
Return formats
137+
--------------
138+
The default return format for API calls is a PHP object.
139+
For API methods returning multiple data (like ```statuses/home_timeline```),
140+
you should cast the reply to array, like this:
141+
142+
```php
143+
$reply = $cb->statuses_homeTimeline();
144+
$data = (array) $reply;
145+
```
146+
147+
Upon your choice, you may also get PHP arrays directly:
148+
149+
```php
150+
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
151+
```
152+
153+
Finally, if you prefer seeing an URL-encoded string as reply, use this:
154+
155+
```php
156+
$cb->setReturnFormat(CODEBIRD_RETURNFORMAT_STRING);
157+
```
158+
159+
Using multiple Codebird instances
160+
---------------------------------
161+
162+
By default, Codebird works with just one instance. This programming paradigma is
163+
called a *singleton*.
164+
165+
Getting the main Codebird object is done like this:
166+
167+
```php
168+
$cb = Codebird::getInstance();
169+
```
170+
171+
If you need to run requests to the Twitter API for multiple users at once,
172+
Codebird supports this as well. Instead of getting the instance like shown above,
173+
create a new object:
174+
175+
```php
176+
$cb1 = new Codebird;
177+
$cb2 = new Codebird;
178+
```
179+
180+
Please note that your OAuth consumer key and secret is shared within
181+
multiple Codebird instances, while the OAuth request and access tokens with their
182+
secrets are *not* shared.

codebird.php

Lines changed: 103 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,16 @@ class Codebird
4545
*/
4646
private static $_instance = null;
4747

48+
/**
49+
* The OAuth consumer key of your registered app
50+
*/
51+
private static $_oauth_consumer_key = null;
52+
53+
/**
54+
* The corresponding consumer secret
55+
*/
56+
private static $_oauth_consumer_secret = null;
57+
4858
/**
4959
* The API endpoint to use
5060
*/
@@ -61,16 +71,6 @@ class Codebird
6171
*/
6272
private $_endpoint_upload = 'https://upload.twitter.com/1/';
6373

64-
/**
65-
* The OAuth consumer key of your registered app
66-
*/
67-
private $_oauth_consumer_key = null;
68-
69-
/**
70-
* The corresponding consumer secret
71-
*/
72-
private $_oauth_consumer_secret = null;
73-
7474
/**
7575
* The Request or access token. Used to sign requests
7676
*/
@@ -91,10 +91,15 @@ class Codebird
9191
*/
9292
private $_statuses_public_timeline_cache = array('timestamp' => false, 'data' => false);
9393

94+
/**
95+
* The file formats that Twitter accepts as image uploads
96+
*/
97+
private $_supported_media_files = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
98+
9499
/**
95100
* The current Codebird version
96101
*/
97-
private $_version = '2.0.3006.2126';
102+
private $_version = '2.1.3007.0006';
98103

99104
/**
100105
* Returns singleton class instance
@@ -111,27 +116,27 @@ public static function getInstance()
111116
}
112117

113118
/**
114-
* Gets the current Codebird version
119+
* Sets the OAuth consumer key and secret (App key)
115120
*
116-
* @return string The version number
121+
* @param string $key OAuth consumer key
122+
* @param string $secret OAuth consumer secret
123+
*
124+
* @return void
117125
*/
118-
public function getVersion()
126+
public static function setConsumerKey($key, $secret)
119127
{
120-
return $this->_version;
128+
self::$_oauth_consumer_key = $key;
129+
self::$_oauth_consumer_secret = $secret;
121130
}
122131

123132
/**
124-
* Sets the OAuth consumer key and secret (App key)
125-
*
126-
* @param string $key OAuth consumer key
127-
* @param string $secret OAuth consumer secret
133+
* Gets the current Codebird version
128134
*
129-
* @return void
135+
* @return string The version number
130136
*/
131-
public function setConsumerKey($key, $secret)
137+
public function getVersion()
132138
{
133-
$this->_oauth_consumer_key = $key;
134-
$this->_oauth_consumer_secret = $secret;
139+
return $this->_version;
135140
}
136141

137142
/**
@@ -221,6 +226,9 @@ public function __call($fn, $params)
221226
$sign = $this->_detectSign($method2);
222227
$multipart = $this->_detectMultipart($method2);
223228

229+
// geek-geek: Now allowing to specify filenames as params
230+
$this->_detectFilenames($method2, $apiparams);
231+
224232
return $this->_callApi($httpmethod, $method, $apiparams, $sign, $multipart);
225233
}
226234

@@ -325,13 +333,13 @@ private function _url($data)
325333
*/
326334
private function _sha1($data)
327335
{
328-
if ($this->_oauth_consumer_secret == null) {
336+
if (self::$_oauth_consumer_secret == null) {
329337
throw new Exception('To generate a hash, the consumer secret must be set.');
330338
}
331339
if (!function_exists('hash_hmac')) {
332340
throw new Exception('To generate a hash, the PHP hash extension must be available.');
333341
}
334-
return base64_encode(hash_hmac('sha1', $data, $this->_oauth_consumer_secret . '&'
342+
return base64_encode(hash_hmac('sha1', $data, self::$_oauth_consumer_secret . '&'
335343
. ($this->_oauth_token_secret != null ? $this->_oauth_token_secret : ''), true));
336344
}
337345

@@ -363,11 +371,11 @@ private function _nonce($length = 8)
363371
*/
364372
private function _sign($httpmethod, $method, $params = array(), $multipart = false)
365373
{
366-
if ($this->_oauth_consumer_key == null) {
374+
if (self::$_oauth_consumer_key == null) {
367375
throw new Exception('To generate a signature, the consumer key must be set.');
368376
}
369377
$sign_params = array(
370-
'consumer_key' => $this->_oauth_consumer_key,
378+
'consumer_key' => self::$_oauth_consumer_key,
371379
'version' => '1.0',
372380
'timestamp' => time(),
373381
'nonce' => $this->_nonce(),
@@ -505,6 +513,7 @@ private function _detectMethod($method)
505513
'statuses/destroy/:id',
506514
'statuses/retweet/:id',
507515
'statuses/update',
516+
'statuses/update_with_media',
508517
// Direct Messages
509518
'direct_messages/new',
510519
// Friends & Followers
@@ -598,6 +607,73 @@ private function _detectMultipart($method)
598607
return in_array($method, $multiparts);
599608
}
600609

610+
/**
611+
* Detects filenames in upload parameters
612+
*
613+
* @param string $method The API method to call
614+
* @param byref array $params The parameters to send along
615+
*
616+
* @return void
617+
*/
618+
private function _detectFilenames($method, &$params)
619+
{
620+
// well, files will only work in multipart methods
621+
if (! $this->_detectMultipart($method)) {
622+
return;
623+
}
624+
625+
// only check specific parameters
626+
$possible_files = array(
627+
// Tweets
628+
'statuses/update_with_media' => 'media[]',
629+
// Accounts
630+
'account/update_profile_background_image' => 'image',
631+
'account/update_profile_image' => 'image'
632+
);
633+
// method might have files?
634+
if (! in_array($method, array_keys($possible_files))) {
635+
return;
636+
}
637+
638+
// check for filenames
639+
$possible_files = explode(' ', $possible_files[$method]);
640+
foreach ($possible_files as $possible_file) {
641+
// is this parameter set currently?
642+
if (! isset($params[$possible_file])) {
643+
continue;
644+
}
645+
// is it an array?
646+
if (is_array($params[$possible_file])) {
647+
throw new Exception('Using URL-encoded parameters is not supported for uploading media.');
648+
continue;
649+
}
650+
// is it a file, a readable one?
651+
if (! @file_exists($params[$possible_file])
652+
|| ! @is_readable($params[$possible_file])
653+
) {
654+
continue;
655+
}
656+
// is it a valid image?
657+
if (! $data = @getimagesize($params[$possible_file])) {
658+
continue;
659+
}
660+
// is it a supported image format?
661+
if (! in_array($data[2], $this->_supported_media_files)) {
662+
continue;
663+
}
664+
// try to read the file
665+
ob_start();
666+
readfile($params[$possible_file]);
667+
$data = ob_get_contents();
668+
ob_end_clean();
669+
if (strlen($data) == 0) {
670+
continue;
671+
}
672+
$params[$possible_file] = $data;
673+
}
674+
}
675+
676+
601677
/**
602678
* Builds the complete API endpoint url
603679
*

0 commit comments

Comments
 (0)
0