Recent Tweets Widget - Version 1.0

Version Description

  • The first version of this plugin! Enjoy! :)

=

Download this release

Release Info

Developer ThemePrince
Plugin Icon 128x128 Recent Tweets Widget
Version 1.0
Comparing to
See all releases

Version 1.0

assets/banner-772x250.png ADDED
Binary file
assets/screenshot-1.png ADDED
Binary file
assets/screenshot-2.png ADDED
Binary file
assets/tweet.png ADDED
Binary file
index.php ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ <?php
2
+ # Silence is golden.
3
+ ?>
readme.txt ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === Recent Tweets Widget ===
2
+ Contributors: themeprince
3
+ Donate link: http://themeprince.com/
4
+ Tags: recent tweets, twitter widget, twitter api v1.1, cache
5
+ Requires at least: 3.4.1
6
+ Tested up to: 3.5.1
7
+ Stable tag: 1.0
8
+ License: GPLv2 or later
9
+ License URI: http://www.gnu.org/licenses/gpl-2.0.html
10
+
11
+ Recent Tweets Widget WordPress plugin for new Twitter API v1.1 with cache, so you won't be rate limited at Twitter!
12
+
13
+ == Description ==
14
+
15
+ Recent Tweets Widget plugin for Twitter API v1.1 with Cache. It uses the new Twitter API v1.1 and stores tweets in the cache. It means that it will read status messages from your database and it doesn't query Twitter.com for every page load so you won't be rate limited. You can set how often you want to update the cache.
16
+
17
+
18
+ == Installation ==
19
+
20
+ 1. Unzip the downloaded zip file
21
+ 2. Upload the `recent-tweets` folder and its contents into the `wp-content/plugins/` directory of your WordPress installation
22
+ 3. Activate Recent Tweets Widget from Plugins page
23
+ 4. Go to your Widgets menu, add `* Recent Tweets` widget to a widget area
24
+ 5. Visit [this link](https://dev.twitter.com/apps/ "Twitter") in a new tab, sign in with your account, click on `Create a new application` and create your own keys in case you don't have already
25
+ 6. Fill all your widget settings
26
+ 7. Enjoy your new Twitter feed! :)
27
+
28
+
29
+ == Frequently Asked Questions ==
30
+
31
+ = How can I get Consumer Key, Consumer Secret, Access Token and Access Token Secret? =
32
+
33
+ You will need to visit [this link](https://dev.twitter.com/apps/ "Twitter"), sign in with your account and create your own keys.
34
+
35
+ == Screenshots ==
36
+
37
+ 1. The widget
38
+ 2. How it looks on frontend page
39
+
40
+ == Changelog ==
41
+
42
+ = 1.0 =
43
+ * The first version of this plugin! Enjoy! :)
44
+
45
+ == Upgrade Notice ==
46
+
47
+ = 1.0 =
48
+ None.
49
+
recent-tweets.php ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ Plugin Name: Recent Tweets Widget
5
+ Plugin URI: http://wordpress.org/extend/plugins/recent-tweets-widget/
6
+ Description: Recent Tweets Widget plugin for Twitter API v1.1 with Cache. It uses the new Twitter API v1.1 and stores tweets in the cache. It means that it will read status messages from your database and it doesn't query Twitter.com for every page load so you won't be rate limited. You can set how often you want to update the cache.
7
+ Version: 1.0
8
+ Author: Theme Prince
9
+ Author URI: http://themeprince.com
10
+ */
11
+
12
+
13
+
14
+ // make sure we don't expose any info if called directly
15
+ if ( !function_exists( 'add_action' ) ) {
16
+ echo 'Hi there! I\'m just a plugin, not much I can do when called directly.';
17
+ exit;
18
+ }
19
+
20
+
21
+ define('TP_RECENT_TWEETS_PATH', plugin_dir_url( __FILE__ ));
22
+
23
+ //register stylesheet for widget
24
+ function tp_twitter_plugin_styles() {
25
+ wp_enqueue_style( 'tp_twitter_plugin_css', TP_RECENT_TWEETS_PATH . 'tp_twitter_plugin.css', array(), '1.0', 'screen' );
26
+ }
27
+ add_action( 'wp_enqueue_scripts', 'tp_twitter_plugin_styles' );
28
+
29
+
30
+ // include widget function
31
+ require_once('widget.php');
32
+
33
+
34
+
35
+
36
+
37
+
38
+ ?>
tp_twitter_plugin.css ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ .tp_recent_tweets {
3
+ float: left;
4
+ clear: left;
5
+ }
6
+
7
+ .tp_recent_tweets li {
8
+ background-image: url('assets/tweet.png');
9
+ background-repeat: no-repeat;
10
+ background-position: 0px 4px;
11
+ padding-left: 30px;
12
+ padding-bottom: 20px;
13
+ float: left;
14
+ clear: left;
15
+ line-height: 20px;
16
+ }
17
+
18
+ .tp_recent_tweets li a {
19
+ font-weight: bold;
20
+ }
21
+
22
+ .tp_recent_tweets .twitter_time {
23
+ color: #999;
24
+ font-size: 12px;
25
+ font-style: italic;
26
+ font-weight: normal;
27
+ }
twitteroauth.php ADDED
@@ -0,0 +1,1130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ * Abraham Williams (abraham@abrah.am) http://abrah.am
5
+ *
6
+ * The first PHP Library to support OAuth for Twitter's REST API.
7
+ */
8
+
9
+ /* Load OAuth lib. You can find it at http://oauth.net */
10
+
11
+ /* Generic exception class
12
+ */
13
+ class OAuthException extends Exception {
14
+ // pass
15
+ }
16
+
17
+ class OAuthConsumer {
18
+ public $key;
19
+ public $secret;
20
+
21
+ function __construct($key, $secret, $callback_url=NULL) {
22
+ $this->key = $key;
23
+ $this->secret = $secret;
24
+ $this->callback_url = $callback_url;
25
+ }
26
+
27
+ function __toString() {
28
+ return "OAuthConsumer[key=$this->key,secret=$this->secret]";
29
+ }
30
+ }
31
+
32
+ class OAuthToken {
33
+ // access tokens and request tokens
34
+ public $key;
35
+ public $secret;
36
+
37
+ /**
38
+ * key = the token
39
+ * secret = the token secret
40
+ */
41
+ function __construct($key, $secret) {
42
+ $this->key = $key;
43
+ $this->secret = $secret;
44
+ }
45
+
46
+ /**
47
+ * generates the basic string serialization of a token that a server
48
+ * would respond to request_token and access_token calls with
49
+ */
50
+ function to_string() {
51
+ return "oauth_token=" .
52
+ OAuthUtil::urlencode_rfc3986($this->key) .
53
+ "&oauth_token_secret=" .
54
+ OAuthUtil::urlencode_rfc3986($this->secret);
55
+ }
56
+
57
+ function __toString() {
58
+ return $this->to_string();
59
+ }
60
+ }
61
+
62
+ /**
63
+ * A class for implementing a Signature Method
64
+ * See section 9 ("Signing Requests") in the spec
65
+ */
66
+ abstract class OAuthSignatureMethod {
67
+ /**
68
+ * Needs to return the name of the Signature Method (ie HMAC-SHA1)
69
+ * @return string
70
+ */
71
+ abstract public function get_name();
72
+
73
+ /**
74
+ * Build up the signature
75
+ * NOTE: The output of this function MUST NOT be urlencoded.
76
+ * the encoding is handled in OAuthRequest when the final
77
+ * request is serialized
78
+ * @param OAuthRequest $request
79
+ * @param OAuthConsumer $consumer
80
+ * @param OAuthToken $token
81
+ * @return string
82
+ */
83
+ abstract public function build_signature($request, $consumer, $token);
84
+
85
+ /**
86
+ * Verifies that a given signature is correct
87
+ * @param OAuthRequest $request
88
+ * @param OAuthConsumer $consumer
89
+ * @param OAuthToken $token
90
+ * @param string $signature
91
+ * @return bool
92
+ */
93
+ public function check_signature($request, $consumer, $token, $signature) {
94
+ $built = $this->build_signature($request, $consumer, $token);
95
+ return $built == $signature;
96
+ }
97
+ }
98
+
99
+ /**
100
+ * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
101
+ * where the Signature Base String is the text and the key is the concatenated values (each first
102
+ * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
103
+ * character (ASCII code 38) even if empty.
104
+ * - Chapter 9.2 ("HMAC-SHA1")
105
+ */
106
+ class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
107
+ function get_name() {
108
+ return "HMAC-SHA1";
109
+ }
110
+
111
+ public function build_signature($request, $consumer, $token) {
112
+ $base_string = $request->get_signature_base_string();
113
+ $request->base_string = $base_string;
114
+
115
+ $key_parts = array(
116
+ $consumer->secret,
117
+ ($token) ? $token->secret : ""
118
+ );
119
+
120
+ $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
121
+ $key = implode('&', $key_parts);
122
+
123
+ return base64_encode(hash_hmac('sha1', $base_string, $key, true));
124
+ }
125
+ }
126
+
127
+ /**
128
+ * The PLAINTEXT method does not provide any security protection and SHOULD only be used
129
+ * over a secure channel such as HTTPS. It does not use the Signature Base String.
130
+ * - Chapter 9.4 ("PLAINTEXT")
131
+ */
132
+ class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
133
+ public function get_name() {
134
+ return "PLAINTEXT";
135
+ }
136
+
137
+ /**
138
+ * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
139
+ * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
140
+ * empty. The result MUST be encoded again.
141
+ * - Chapter 9.4.1 ("Generating Signatures")
142
+ *
143
+ * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
144
+ * OAuthRequest handles this!
145
+ */
146
+ public function build_signature($request, $consumer, $token) {
147
+ $key_parts = array(
148
+ $consumer->secret,
149
+ ($token) ? $token->secret : ""
150
+ );
151
+
152
+ $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
153
+ $key = implode('&', $key_parts);
154
+ $request->base_string = $key;
155
+
156
+ return $key;
157
+ }
158
+ }
159
+
160
+ /**
161
+ * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
162
+ * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
163
+ * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
164
+ * verified way to the Service Provider, in a manner which is beyond the scope of this
165
+ * specification.
166
+ * - Chapter 9.3 ("RSA-SHA1")
167
+ */
168
+ abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
169
+ public function get_name() {
170
+ return "RSA-SHA1";
171
+ }
172
+
173
+ // Up to the SP to implement this lookup of keys. Possible ideas are:
174
+ // (1) do a lookup in a table of trusted certs keyed off of consumer
175
+ // (2) fetch via http using a url provided by the requester
176
+ // (3) some sort of specific discovery code based on request
177
+ //
178
+ // Either way should return a string representation of the certificate
179
+ protected abstract function fetch_public_cert(&$request);
180
+
181
+ // Up to the SP to implement this lookup of keys. Possible ideas are:
182
+ // (1) do a lookup in a table of trusted certs keyed off of consumer
183
+ //
184
+ // Either way should return a string representation of the certificate
185
+ protected abstract function fetch_private_cert(&$request);
186
+
187
+ public function build_signature($request, $consumer, $token) {
188
+ $base_string = $request->get_signature_base_string();
189
+ $request->base_string = $base_string;
190
+
191
+ // Fetch the private key cert based on the request
192
+ $cert = $this->fetch_private_cert($request);
193
+
194
+ // Pull the private key ID from the certificate
195
+ $privatekeyid = openssl_get_privatekey($cert);
196
+
197
+ // Sign using the key
198
+ $ok = openssl_sign($base_string, $signature, $privatekeyid);
199
+
200
+ // Release the key resource
201
+ openssl_free_key($privatekeyid);
202
+
203
+ return base64_encode($signature);
204
+ }
205
+
206
+ public function check_signature($request, $consumer, $token, $signature) {
207
+ $decoded_sig = base64_decode($signature);
208
+
209
+ $base_string = $request->get_signature_base_string();
210
+
211
+ // Fetch the public key cert based on the request
212
+ $cert = $this->fetch_public_cert($request);
213
+
214
+ // Pull the public key ID from the certificate
215
+ $publickeyid = openssl_get_publickey($cert);
216
+
217
+ // Check the computed signature against the one passed in the query
218
+ $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
219
+
220
+ // Release the key resource
221
+ openssl_free_key($publickeyid);
222
+
223
+ return $ok == 1;
224
+ }
225
+ }
226
+
227
+ class OAuthRequest {
228
+ private $parameters;
229
+ private $http_method;
230
+ private $http_url;
231
+ // for debug purposes
232
+ public $base_string;
233
+ public static $version = '1.0';
234
+ public static $POST_INPUT = 'php://input';
235
+
236
+ function __construct($http_method, $http_url, $parameters=NULL) {
237
+ @$parameters or $parameters = array();
238
+ $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
239
+ $this->parameters = $parameters;
240
+ $this->http_method = $http_method;
241
+ $this->http_url = $http_url;
242
+ }
243
+
244
+
245
+ /**
246
+ * attempt to build up a request from what was passed to the server
247
+ */
248
+ public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
249
+ $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
250
+ ? 'http'
251
+ : 'https';
252
+ @$http_url or $http_url = $scheme .
253
+ '://' . $_SERVER['HTTP_HOST'] .
254
+ ':' .
255
+ $_SERVER['SERVER_PORT'] .
256
+ $_SERVER['REQUEST_URI'];
257
+ @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
258
+
259
+ // We weren't handed any parameters, so let's find the ones relevant to
260
+ // this request.
261
+ // If you run XML-RPC or similar you should use this to provide your own
262
+ // parsed parameter-list
263
+ if (!$parameters) {
264
+ // Find request headers
265
+ $request_headers = OAuthUtil::get_headers();
266
+
267
+ // Parse the query-string to find GET parameters
268
+ $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
269
+
270
+ // It's a POST request of the proper content-type, so parse POST
271
+ // parameters and add those overriding any duplicates from GET
272
+ if ($http_method == "POST"
273
+ && @strstr($request_headers["Content-Type"],
274
+ "application/x-www-form-urlencoded")
275
+ ) {
276
+ $post_data = OAuthUtil::parse_parameters(
277
+ file_get_contents(self::$POST_INPUT)
278
+ );
279
+ $parameters = array_merge($parameters, $post_data);
280
+ }
281
+
282
+ // We have a Authorization-header with OAuth data. Parse the header
283
+ // and add those overriding any duplicates from GET or POST
284
+ if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
285
+ $header_parameters = OAuthUtil::split_header(
286
+ $request_headers['Authorization']
287
+ );
288
+ $parameters = array_merge($parameters, $header_parameters);
289
+ }
290
+
291
+ }
292
+
293
+ return new OAuthRequest($http_method, $http_url, $parameters);
294
+ }
295
+
296
+ /**
297
+ * pretty much a helper function to set up the request
298
+ */
299
+ public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
300
+ @$parameters or $parameters = array();
301
+ $defaults = array("oauth_version" => OAuthRequest::$version,
302
+ "oauth_nonce" => OAuthRequest::generate_nonce(),
303
+ "oauth_timestamp" => OAuthRequest::generate_timestamp(),
304
+ "oauth_consumer_key" => $consumer->key);
305
+ if ($token)
306
+ $defaults['oauth_token'] = $token->key;
307
+
308
+ $parameters = array_merge($defaults, $parameters);
309
+
310
+ return new OAuthRequest($http_method, $http_url, $parameters);
311
+ }
312
+
313
+ public function set_parameter($name, $value, $allow_duplicates = true) {
314
+ if ($allow_duplicates && isset($this->parameters[$name])) {
315
+ // We have already added parameter(s) with this name, so add to the list
316
+ if (is_scalar($this->parameters[$name])) {
317
+ // This is the first duplicate, so transform scalar (string)
318
+ // into an array so we can add the duplicates
319
+ $this->parameters[$name] = array($this->parameters[$name]);
320
+ }
321
+
322
+ $this->parameters[$name][] = $value;
323
+ } else {
324
+ $this->parameters[$name] = $value;
325
+ }
326
+ }
327
+
328
+ public function get_parameter($name) {
329
+ return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
330
+ }
331
+
332
+ public function get_parameters() {
333
+ return $this->parameters;
334
+ }
335
+
336
+ public function unset_parameter($name) {
337
+ unset($this->parameters[$name]);
338
+ }
339
+
340
+ /**
341
+ * The request parameters, sorted and concatenated into a normalized string.
342
+ * @return string
343
+ */
344
+ public function get_signable_parameters() {
345
+ // Grab all parameters
346
+ $params = $this->parameters;
347
+
348
+ // Remove oauth_signature if present
349
+ // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
350
+ if (isset($params['oauth_signature'])) {
351
+ unset($params['oauth_signature']);
352
+ }
353
+
354
+ return OAuthUtil::build_http_query($params);
355
+ }
356
+
357
+ /**
358
+ * Returns the base string of this request
359
+ *
360
+ * The base string defined as the method, the url
361
+ * and the parameters (normalized), each urlencoded
362
+ * and the concated with &.
363
+ */
364
+ public function get_signature_base_string() {
365
+ $parts = array(
366
+ $this->get_normalized_http_method(),
367
+ $this->get_normalized_http_url(),
368
+ $this->get_signable_parameters()
369
+ );
370
+
371
+ $parts = OAuthUtil::urlencode_rfc3986($parts);
372
+
373
+ return implode('&', $parts);
374
+ }
375
+
376
+ /**
377
+ * just uppercases the http method
378
+ */
379
+ public function get_normalized_http_method() {
380
+ return strtoupper($this->http_method);
381
+ }
382
+
383
+ /**
384
+ * parses the url and rebuilds it to be
385
+ * scheme://host/path
386
+ */
387
+ public function get_normalized_http_url() {
388
+ $parts = parse_url($this->http_url);
389
+
390
+ $port = @$parts['port'];
391
+ $scheme = $parts['scheme'];
392
+ $host = $parts['host'];
393
+ $path = @$parts['path'];
394
+
395
+ $port or $port = ($scheme == 'https') ? '443' : '80';
396
+
397
+ if (($scheme == 'https' && $port != '443')
398
+ || ($scheme == 'http' && $port != '80')) {
399
+ $host = "$host:$port";
400
+ }
401
+ return "$scheme://$host$path";
402
+ }
403
+
404
+ /**
405
+ * builds a url usable for a GET request
406
+ */
407
+ public function to_url() {
408
+ $post_data = $this->to_postdata();
409
+ $out = $this->get_normalized_http_url();
410
+ if ($post_data) {
411
+ $out .= '?'.$post_data;
412
+ }
413
+ return $out;
414
+ }
415
+
416
+ /**
417
+ * builds the data one would send in a POST request
418
+ */
419
+ public function to_postdata() {
420
+ return OAuthUtil::build_http_query($this->parameters);
421
+ }
422
+
423
+ /**
424
+ * builds the Authorization: header
425
+ */
426
+ public function to_header($realm=null) {
427
+ $first = true;
428
+ if($realm) {
429
+ $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
430
+ $first = false;
431
+ } else
432
+ $out = 'Authorization: OAuth';
433
+
434
+ $total = array();
435
+ foreach ($this->parameters as $k => $v) {
436
+ if (substr($k, 0, 5) != "oauth") continue;
437
+ if (is_array($v)) {
438
+ throw new OAuthException('Arrays not supported in headers');
439
+ }
440
+ $out .= ($first) ? ' ' : ',';
441
+ $out .= OAuthUtil::urlencode_rfc3986($k) .
442
+ '="' .
443
+ OAuthUtil::urlencode_rfc3986($v) .
444
+ '"';
445
+ $first = false;
446
+ }
447
+ return $out;
448
+ }
449
+
450
+ public function __toString() {
451
+ return $this->to_url();
452
+ }
453
+
454
+
455
+ public function sign_request($signature_method, $consumer, $token) {
456
+ $this->set_parameter(
457
+ "oauth_signature_method",
458
+ $signature_method->get_name(),
459
+ false
460
+ );
461
+ $signature = $this->build_signature($signature_method, $consumer, $token);
462
+ $this->set_parameter("oauth_signature", $signature, false);
463
+ }
464
+
465
+ public function build_signature($signature_method, $consumer, $token) {
466
+ $signature = $signature_method->build_signature($this, $consumer, $token);
467
+ return $signature;
468
+ }
469
+
470
+ /**
471
+ * util function: current timestamp
472
+ */
473
+ private static function generate_timestamp() {
474
+ return time();
475
+ }
476
+
477
+ /**
478
+ * util function: current nonce
479
+ */
480
+ private static function generate_nonce() {
481
+ $mt = microtime();
482
+ $rand = mt_rand();
483
+
484
+ return md5($mt . $rand); // md5s look nicer than numbers
485
+ }
486
+ }
487
+
488
+ class OAuthServer {
489
+ protected $timestamp_threshold = 300; // in seconds, five minutes
490
+ protected $version = '1.0'; // hi blaine
491
+ protected $signature_methods = array();
492
+
493
+ protected $data_store;
494
+
495
+ function __construct($data_store) {
496
+ $this->data_store = $data_store;
497
+ }
498
+
499
+ public function add_signature_method($signature_method) {
500
+ $this->signature_methods[$signature_method->get_name()] =
501
+ $signature_method;
502
+ }
503
+
504
+ // high level functions
505
+
506
+ /**
507
+ * process a request_token request
508
+ * returns the request token on success
509
+ */
510
+ public function fetch_request_token(&$request) {
511
+ $this->get_version($request);
512
+
513
+ $consumer = $this->get_consumer($request);
514
+
515
+ // no token required for the initial token request
516
+ $token = NULL;
517
+
518
+ $this->check_signature($request, $consumer, $token);
519
+
520
+ // Rev A change
521
+ $callback = $request->get_parameter('oauth_callback');
522
+ $new_token = $this->data_store->new_request_token($consumer, $callback);
523
+
524
+ return $new_token;
525
+ }
526
+
527
+ /**
528
+ * process an access_token request
529
+ * returns the access token on success
530
+ */
531
+ public function fetch_access_token(&$request) {
532
+ $this->get_version($request);
533
+
534
+ $consumer = $this->get_consumer($request);
535
+
536
+ // requires authorized request token
537
+ $token = $this->get_token($request, $consumer, "request");
538
+
539
+ $this->check_signature($request, $consumer, $token);
540
+
541
+ // Rev A change
542
+ $verifier = $request->get_parameter('oauth_verifier');
543
+ $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
544
+
545
+ return $new_token;
546
+ }
547
+
548
+ /**
549
+ * verify an api call, checks all the parameters
550
+ */
551
+ public function verify_request(&$request) {
552
+ $this->get_version($request);
553
+ $consumer = $this->get_consumer($request);
554
+ $token = $this->get_token($request, $consumer, "access");
555
+ $this->check_signature($request, $consumer, $token);
556
+ return array($consumer, $token);
557
+ }
558
+
559
+ // Internals from here
560
+ /**
561
+ * version 1
562
+ */
563
+ private function get_version(&$request) {
564
+ $version = $request->get_parameter("oauth_version");
565
+ if (!$version) {
566
+ // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
567
+ // Chapter 7.0 ("Accessing Protected Ressources")
568
+ $version = '1.0';
569
+ }
570
+ if ($version !== $this->version) {
571
+ throw new OAuthException("OAuth version '$version' not supported");
572
+ }
573
+ return $version;
574
+ }
575
+
576
+ /**
577
+ * figure out the signature with some defaults
578
+ */
579
+ private function get_signature_method(&$request) {
580
+ $signature_method =
581
+ @$request->get_parameter("oauth_signature_method");
582
+
583
+ if (!$signature_method) {
584
+ // According to chapter 7 ("Accessing Protected Ressources") the signature-method
585
+ // parameter is required, and we can't just fallback to PLAINTEXT
586
+ throw new OAuthException('No signature method parameter. This parameter is required');
587
+ }
588
+
589
+ if (!in_array($signature_method,
590
+ array_keys($this->signature_methods))) {
591
+ throw new OAuthException(
592
+ "Signature method '$signature_method' not supported " .
593
+ "try one of the following: " .
594
+ implode(", ", array_keys($this->signature_methods))
595
+ );
596
+ }
597
+ return $this->signature_methods[$signature_method];
598
+ }
599
+
600
+ /**
601
+ * try to find the consumer for the provided request's consumer key
602
+ */
603
+ private function get_consumer(&$request) {
604
+ $consumer_key = @$request->get_parameter("oauth_consumer_key");
605
+ if (!$consumer_key) {
606
+ throw new OAuthException("Invalid consumer key");
607
+ }
608
+
609
+ $consumer = $this->data_store->lookup_consumer($consumer_key);
610
+ if (!$consumer) {
611
+ throw new OAuthException("Invalid consumer");
612
+ }
613
+
614
+ return $consumer;
615
+ }
616
+
617
+ /**
618
+ * try to find the token for the provided request's token key
619
+ */
620
+ private function get_token(&$request, $consumer, $token_type="access") {
621
+ $token_field = @$request->get_parameter('oauth_token');
622
+ $token = $this->data_store->lookup_token(
623
+ $consumer, $token_type, $token_field
624
+ );
625
+ if (!$token) {
626
+ throw new OAuthException("Invalid $token_type token: $token_field");
627
+ }
628
+ return $token;
629
+ }
630
+
631
+ /**
632
+ * all-in-one function to check the signature on a request
633
+ * should guess the signature method appropriately
634
+ */
635
+ private function check_signature(&$request, $consumer, $token) {
636
+ // this should probably be in a different method
637
+ $timestamp = @$request->get_parameter('oauth_timestamp');
638
+ $nonce = @$request->get_parameter('oauth_nonce');
639
+
640
+ $this->check_timestamp($timestamp);
641
+ $this->check_nonce($consumer, $token, $nonce, $timestamp);
642
+
643
+ $signature_method = $this->get_signature_method($request);
644
+
645
+ $signature = $request->get_parameter('oauth_signature');
646
+ $valid_sig = $signature_method->check_signature(
647
+ $request,
648
+ $consumer,
649
+ $token,
650
+ $signature
651
+ );
652
+
653
+ if (!$valid_sig) {
654
+ throw new OAuthException("Invalid signature");
655
+ }
656
+ }
657
+
658
+ /**
659
+ * check that the timestamp is new enough
660
+ */
661
+ private function check_timestamp($timestamp) {
662
+ if( ! $timestamp )
663
+ throw new OAuthException(
664
+ 'Missing timestamp parameter. The parameter is required'
665
+ );
666
+
667
+ // verify that timestamp is recentish
668
+ $now = time();
669
+ if (abs($now - $timestamp) > $this->timestamp_threshold) {
670
+ throw new OAuthException(
671
+ "Expired timestamp, yours $timestamp, ours $now"
672
+ );
673
+ }
674
+ }
675
+
676
+ /**
677
+ * check that the nonce is not repeated
678
+ */
679
+ private function check_nonce($consumer, $token, $nonce, $timestamp) {
680
+ if( ! $nonce )
681
+ throw new OAuthException(
682
+ 'Missing nonce parameter. The parameter is required'
683
+ );
684
+
685
+ // verify that the nonce is uniqueish
686
+ $found = $this->data_store->lookup_nonce(
687
+ $consumer,
688
+ $token,
689
+ $nonce,
690
+ $timestamp
691
+ );
692
+ if ($found) {
693
+ throw new OAuthException("Nonce already used: $nonce");
694
+ }
695
+ }
696
+
697
+ }
698
+
699
+ class OAuthDataStore {
700
+ function lookup_consumer($consumer_key) {
701
+ // implement me
702
+ }
703
+
704
+ function lookup_token($consumer, $token_type, $token) {
705
+ // implement me
706
+ }
707
+
708
+ function lookup_nonce($consumer, $token, $nonce, $timestamp) {
709
+ // implement me
710
+ }
711
+
712
+ function new_request_token($consumer, $callback = null) {
713
+ // return a new token attached to this consumer
714
+ }
715
+
716
+ function new_access_token($token, $consumer, $verifier = null) {
717
+ // return a new access token attached to this consumer
718
+ // for the user associated with this token if the request token
719
+ // is authorized
720
+ // should also invalidate the request token
721
+ }
722
+
723
+ }
724
+
725
+ class OAuthUtil {
726
+ public static function urlencode_rfc3986($input) {
727
+ if (is_array($input)) {
728
+ return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
729
+ } else if (is_scalar($input)) {
730
+ return str_replace(
731
+ '+',
732
+ ' ',
733
+ str_replace('%7E', '~', rawurlencode($input))
734
+ );
735
+ } else {
736
+ return '';
737
+ }
738
+ }
739
+
740
+
741
+ // This decode function isn't taking into consideration the above
742
+ // modifications to the encoding process. However, this method doesn't
743
+ // seem to be used anywhere so leaving it as is.
744
+ public static function urldecode_rfc3986($string) {
745
+ return urldecode($string);
746
+ }
747
+
748
+ // Utility function for turning the Authorization: header into
749
+ // parameters, has to do some unescaping
750
+ // Can filter out any non-oauth parameters if needed (default behaviour)
751
+ public static function split_header($header, $only_allow_oauth_parameters = true) {
752
+ $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
753
+ $offset = 0;
754
+ $params = array();
755
+ while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
756
+ $match = $matches[0];
757
+ $header_name = $matches[2][0];
758
+ $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
759
+ if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
760
+ $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
761
+ }
762
+ $offset = $match[1] + strlen($match[0]);
763
+ }
764
+
765
+ if (isset($params['realm'])) {
766
+ unset($params['realm']);
767
+ }
768
+
769
+ return $params;
770
+ }
771
+
772
+ // helper to try to sort out headers for people who aren't running apache
773
+ public static function get_headers() {
774
+ if (function_exists('apache_request_headers')) {
775
+ // we need this to get the actual Authorization: header
776
+ // because apache tends to tell us it doesn't exist
777
+ $headers = apache_request_headers();
778
+
779
+ // sanitize the output of apache_request_headers because
780
+ // we always want the keys to be Cased-Like-This and arh()
781
+ // returns the headers in the same case as they are in the
782
+ // request
783
+ $out = array();
784
+ foreach( $headers AS $key => $value ) {
785
+ $key = str_replace(
786
+ " ",
787
+ "-",
788
+ ucwords(strtolower(str_replace("-", " ", $key)))
789
+ );
790
+ $out[$key] = $value;
791
+ }
792
+ } else {
793
+ // otherwise we don't have apache and are just going to have to hope
794
+ // that $_SERVER actually contains what we need
795
+ $out = array();
796
+ if( isset($_SERVER['CONTENT_TYPE']) )
797
+ $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
798
+ if( isset($_ENV['CONTENT_TYPE']) )
799
+ $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
800
+
801
+ foreach ($_SERVER as $key => $value) {
802
+ if (substr($key, 0, 5) == "HTTP_") {
803
+ // this is chaos, basically it is just there to capitalize the first
804
+ // letter of every word that is not an initial HTTP and strip HTTP
805
+ // code from przemek
806
+ $key = str_replace(
807
+ " ",
808
+ "-",
809
+ ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
810
+ );
811
+ $out[$key] = $value;
812
+ }
813
+ }
814
+ }
815
+ return $out;
816
+ }
817
+
818
+ // This function takes a input like a=b&a=c&d=e and returns the parsed
819
+ // parameters like this
820
+ // array('a' => array('b','c'), 'd' => 'e')
821
+ public static function parse_parameters( $input ) {
822
+ if (!isset($input) || !$input) return array();
823
+
824
+ $pairs = explode('&', $input);
825
+
826
+ $parsed_parameters = array();
827
+ foreach ($pairs as $pair) {
828
+ $split = explode('=', $pair, 2);
829
+ $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
830
+ $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
831
+
832
+ if (isset($parsed_parameters[$parameter])) {
833
+ // We have already recieved parameter(s) with this name, so add to the list
834
+ // of parameters with this name
835
+
836
+ if (is_scalar($parsed_parameters[$parameter])) {
837
+ // This is the first duplicate, so transform scalar (string) into an array
838
+ // so we can add the duplicates
839
+ $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
840
+ }
841
+
842
+ $parsed_parameters[$parameter][] = $value;
843
+ } else {
844
+ $parsed_parameters[$parameter] = $value;
845
+ }
846
+ }
847
+ return $parsed_parameters;
848
+ }
849
+
850
+ public static function build_http_query($params) {
851
+ if (!$params) return '';
852
+
853
+ // Urlencode both keys and values
854
+ $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
855
+ $values = OAuthUtil::urlencode_rfc3986(array_values($params));
856
+ $params = array_combine($keys, $values);
857
+
858
+ // Parameters are sorted by name, using lexicographical byte value ordering.
859
+ // Ref: Spec: 9.1.1 (1)
860
+ uksort($params, 'strcmp');
861
+
862
+ $pairs = array();
863
+ foreach ($params as $parameter => $value) {
864
+ if (is_array($value)) {
865
+ // If two or more parameters share the same name, they are sorted by their value
866
+ // Ref: Spec: 9.1.1 (1)
867
+ natsort($value);
868
+ foreach ($value as $duplicate_value) {
869
+ $pairs[] = $parameter . '=' . $duplicate_value;
870
+ }
871
+ } else {
872
+ $pairs[] = $parameter . '=' . $value;
873
+ }
874
+ }
875
+ // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
876
+ // Each name-value pair is separated by an '&' character (ASCII code 38)
877
+ return implode('&', $pairs);
878
+ }
879
+ }
880
+
881
+
882
+
883
+
884
+
885
+
886
+
887
+
888
+
889
+
890
+
891
+
892
+
893
+
894
+
895
+
896
+
897
+ /**
898
+ * Twitter OAuth class
899
+ */
900
+ class TwitterOAuth {
901
+ /* Contains the last HTTP status code returned. */
902
+ public $http_code;
903
+ /* Contains the last API call. */
904
+ public $url;
905
+ /* Set up the API root URL. */
906
+ public $host = "https://api.twitter.com/1/";
907
+ /* Set timeout default. */
908
+ public $timeout = 30;
909
+ /* Set connect timeout. */
910
+ public $connecttimeout = 30;
911
+ /* Verify SSL Cert. */
912
+ public $ssl_verifypeer = FALSE;
913
+ /* Respons format. */
914
+ public $format = 'json';
915
+ /* Decode returned json data. */
916
+ public $decode_json = TRUE;
917
+ /* Contains the last HTTP headers returned. */
918
+ public $http_info;
919
+ /* Set the useragnet. */
920
+ public $useragent = 'TwitterOAuth v0.2.0-beta2';
921
+ /* Immediately retry the API call if the response was not successful. */
922
+ //public $retry = TRUE;
923
+
924
+
925
+
926
+
927
+ /**
928
+ * Set API URLS
929
+ */
930
+ function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; }
931
+ function authenticateURL() { return 'https://api.twitter.com/oauth/authenticate'; }
932
+ function authorizeURL() { return 'https://api.twitter.com/oauth/authorize'; }
933
+ function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; }
934
+
935
+ /**
936
+ * Debug helpers
937
+ */
938
+ function lastStatusCode() { return $this->http_status; }
939
+ function lastAPICall() { return $this->last_api_call; }
940
+
941
+ /**
942
+ * construct TwitterOAuth object
943
+ */
944
+ function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
945
+ $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
946
+ $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
947
+ if (!empty($oauth_token) && !empty($oauth_token_secret)) {
948
+ $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
949
+ } else {
950
+ $this->token = NULL;
951
+ }
952
+ }
953
+
954
+
955
+ /**
956
+ * Get a request_token from Twitter
957
+ *
958
+ * @returns a key/value array containing oauth_token and oauth_token_secret
959
+ */
960
+ function getRequestToken($oauth_callback = NULL) {
961
+ $parameters = array();
962
+ if (!empty($oauth_callback)) {
963
+ $parameters['oauth_callback'] = $oauth_callback;
964
+ }
965
+ $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
966
+ $token = OAuthUtil::parse_parameters($request);
967
+ $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
968
+ return $token;
969
+ }
970
+
971
+ /**
972
+ * Get the authorize URL
973
+ *
974
+ * @returns a string
975
+ */
976
+ function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
977
+ if (is_array($token)) {
978
+ $token = $token['oauth_token'];
979
+ }
980
+ if (empty($sign_in_with_twitter)) {
981
+ return $this->authorizeURL() . "?oauth_token={$token}";
982
+ } else {
983
+ return $this->authenticateURL() . "?oauth_token={$token}";
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Exchange request token and secret for an access token and
989
+ * secret, to sign API calls.
990
+ *
991
+ * @returns array("oauth_token" => "the-access-token",
992
+ * "oauth_token_secret" => "the-access-secret",
993
+ * "user_id" => "9436992",
994
+ * "screen_name" => "abraham")
995
+ */
996
+ function getAccessToken($oauth_verifier = FALSE) {
997
+ $parameters = array();
998
+ if (!empty($oauth_verifier)) {
999
+ $parameters['oauth_verifier'] = $oauth_verifier;
1000
+ }
1001
+ $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
1002
+ $token = OAuthUtil::parse_parameters($request);
1003
+ $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
1004
+ return $token;
1005
+ }
1006
+
1007
+ /**
1008
+ * One time exchange of username and password for access token and secret.
1009
+ *
1010
+ * @returns array("oauth_token" => "the-access-token",
1011
+ * "oauth_token_secret" => "the-access-secret",
1012
+ * "user_id" => "9436992",
1013
+ * "screen_name" => "abraham",
1014
+ * "x_auth_expires" => "0")
1015
+ */
1016
+ function getXAuthToken($username, $password) {
1017
+ $parameters = array();
1018
+ $parameters['x_auth_username'] = $username;
1019
+ $parameters['x_auth_password'] = $password;
1020
+ $parameters['x_auth_mode'] = 'client_auth';
1021
+ $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters);
1022
+ $token = OAuthUtil::parse_parameters($request);
1023
+ $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
1024
+ return $token;
1025
+ }
1026
+
1027
+ /**
1028
+ * GET wrapper for oAuthRequest.
1029
+ */
1030
+ function get($url, $parameters = array()) {
1031
+ $response = $this->oAuthRequest($url, 'GET', $parameters);
1032
+ if ($this->format === 'json' && $this->decode_json) {
1033
+ return json_decode($response);
1034
+ }
1035
+ return $response;
1036
+ }
1037
+
1038
+ /**
1039
+ * POST wrapper for oAuthRequest.
1040
+ */
1041
+ function post($url, $parameters = array()) {
1042
+ $response = $this->oAuthRequest($url, 'POST', $parameters);
1043
+ if ($this->format === 'json' && $this->decode_json) {
1044
+ return json_decode($response);
1045
+ }
1046
+ return $response;
1047
+ }
1048
+
1049
+ /**
1050
+ * DELETE wrapper for oAuthReqeust.
1051
+ */
1052
+ function delete($url, $parameters = array()) {
1053
+ $response = $this->oAuthRequest($url, 'DELETE', $parameters);
1054
+ if ($this->format === 'json' && $this->decode_json) {
1055
+ return json_decode($response);
1056
+ }
1057
+ return $response;
1058
+ }
1059
+
1060
+ /**
1061
+ * Format and sign an OAuth / API request
1062
+ */
1063
+ function oAuthRequest($url, $method, $parameters) {
1064
+ if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
1065
+ $url = "{$this->host}{$url}.{$this->format}";
1066
+ }
1067
+ $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
1068
+ $request->sign_request($this->sha1_method, $this->consumer, $this->token);
1069
+ switch ($method) {
1070
+ case 'GET':
1071
+ return $this->http($request->to_url(), 'GET');
1072
+ default:
1073
+ return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * Make an HTTP request
1079
+ *
1080
+ * @return API results
1081
+ */
1082
+ function http($url, $method, $postfields = NULL) {
1083
+ $this->http_info = array();
1084
+ $ci = curl_init();
1085
+ /* Curl settings */
1086
+ curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
1087
+ curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
1088
+ curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
1089
+ curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
1090
+ curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
1091
+ curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
1092
+ curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
1093
+ curl_setopt($ci, CURLOPT_HEADER, FALSE);
1094
+
1095
+ switch ($method) {
1096
+ case 'POST':
1097
+ curl_setopt($ci, CURLOPT_POST, TRUE);
1098
+ if (!empty($postfields)) {
1099
+ curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
1100
+ }
1101
+ break;
1102
+ case 'DELETE':
1103
+ curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
1104
+ if (!empty($postfields)) {
1105
+ $url = "{$url}?{$postfields}";
1106
+ }
1107
+ }
1108
+
1109
+ curl_setopt($ci, CURLOPT_URL, $url);
1110
+ $response = curl_exec($ci);
1111
+ $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
1112
+ $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
1113
+ $this->url = $url;
1114
+ curl_close ($ci);
1115
+ return $response;
1116
+ }
1117
+
1118
+ /**
1119
+ * Get the header info to store.
1120
+ */
1121
+ function getHeader($ch, $header) {
1122
+ $i = strpos($header, ':');
1123
+ if (!empty($i)) {
1124
+ $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
1125
+ $value = trim(substr($header, $i + 2));
1126
+ $this->http_header[$key] = $value;
1127
+ }
1128
+ return strlen($header);
1129
+ }
1130
+ }
widget.php ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+
4
+ // widget function
5
+ class tp_widget_recent_tweets extends WP_Widget {
6
+
7
+ public function __construct() {
8
+ parent::__construct(
9
+ 'tp_widget_recent_tweets', // Base ID
10
+ '* Recent Tweets', // Name
11
+ array( 'description' => __( 'Display recent tweets', 'ingrid' ), ) // Args
12
+ );
13
+ }
14
+
15
+
16
+ //widget output
17
+ public function widget($args, $instance) {
18
+ extract($args);
19
+ if(!empty($instance['title'])){ $title = apply_filters( 'widget_title', $instance['title'] ); }
20
+
21
+ echo $before_widget;
22
+ if ( ! empty( $title ) ){ echo $before_title . $title . $after_title; }
23
+
24
+
25
+ //check settings and die if not set
26
+ if(empty($instance['consumerkey']) || empty($instance['consumersecret']) || empty($instance['accesstoken']) || empty($instance['accesstokensecret']) || empty($instance['cachetime']) || empty($instance['username'])){
27
+ echo '<strong>Please fill all widget settings!</strong>' . $after_widget;
28
+ return;
29
+ }
30
+
31
+
32
+ //check if cache needs update
33
+ $tp_twitter_plugin_last_cache_time = get_option('tp_twitter_plugin_last_cache_time');
34
+ $diff = time() - $tp_twitter_plugin_last_cache_time;
35
+ $crt = $instance['cachetime'] * 3600;
36
+
37
+ // yes, it needs update
38
+ if($diff >= $crt || empty($tp_twitter_plugin_last_cache_time)){
39
+
40
+ if(!require_once('twitteroauth.php')){
41
+ echo '<strong>Couldn\'t find twitteroauth.php!</strong>' . $after_widget;
42
+ return;
43
+ }
44
+
45
+ function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
46
+ $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
47
+ return $connection;
48
+ }
49
+
50
+
51
+ $connection = getConnectionWithAccessToken($instance['consumerkey'], $instance['consumersecret'], $instance['accesstoken'], $instance['accesstokensecret']);
52
+ $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$instance['username']."&count=10") or die('Couldn\'t retrieve tweets! Wrong username?');
53
+
54
+
55
+ if(!empty($tweets->errors)){
56
+ if($tweets->errors[0]->message == 'Invalid or expired token'){
57
+ echo '<strong>'.$tweets->errors[0]->message.'!</strong><br />You\'ll need to regenerate it <a href="https://dev.twitter.com/apps" target="_blank">here</a>!' . $after_widget;
58
+ }else{
59
+ echo '<strong>'.$tweets->errors[0]->message.'</strong>' . $after_widget;
60
+ }
61
+ return;
62
+ }
63
+
64
+ for($i = 0;$i <= count($tweets); $i++){
65
+ if(!empty($tweets[$i])){
66
+ $tweets_array[$i]['created_at'] = $tweets[$i]->created_at;
67
+ $tweets_array[$i]['text'] = $tweets[$i]->text;
68
+ $tweets_array[$i]['status_id'] = $tweets[$i]->id_str;
69
+ }
70
+ }
71
+
72
+ //save tweets to wp option
73
+ update_option('tp_twitter_plugin_tweets',serialize($tweets_array));
74
+ update_option('tp_twitter_plugin_last_cache_time',time());
75
+
76
+ echo '<!-- twitter cache has been updated! -->';
77
+ }
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+ //convert links to clickable format
87
+ function convert_links($status,$targetBlank=true,$linkMaxLen=250){
88
+
89
+ // the target
90
+ $target=$targetBlank ? " target=\"_blank\" " : "";
91
+
92
+ // convert link to url
93
+ $status = preg_replace("/((http:\/\/|https:\/\/)[^ )
94
+ ]+)/e", "'<a href=\"$1\" title=\"$1\" $target >'. ((strlen('$1')>=$linkMaxLen ? substr('$1',0,$linkMaxLen).'...':'$1')).'</a>'", $status);
95
+
96
+ // convert @ to follow
97
+ $status = preg_replace("/(@([_a-z0-9\-]+))/i","<a href=\"http://twitter.com/$2\" title=\"Follow $2\" $target >$1</a>",$status);
98
+
99
+ // convert # to search
100
+ $status = preg_replace("/(#([_a-z0-9\-]+))/i","<a href=\"https://twitter.com/search?q=$2\" title=\"Search $1\" $target >$1</a>",$status);
101
+
102
+ // return the status
103
+ return $status;
104
+ }
105
+
106
+
107
+ //convert dates to readable format
108
+ function relative_time($a) {
109
+ //get current timestampt
110
+ $b = strtotime("now");
111
+ //get timestamp when tweet created
112
+ $c = strtotime($a);
113
+ //get difference
114
+ $d = $b - $c;
115
+ //calculate different time values
116
+ $minute = 60;
117
+ $hour = $minute * 60;
118
+ $day = $hour * 24;
119
+ $week = $day * 7;
120
+
121
+ if(is_numeric($d) && $d > 0) {
122
+ //if less then 3 seconds
123
+ if($d < 3) return "right now";
124
+ //if less then minute
125
+ if($d < $minute) return floor($d) . " seconds ago";
126
+ //if less then 2 minutes
127
+ if($d < $minute * 2) return "about 1 minute ago";
128
+ //if less then hour
129
+ if($d < $hour) return floor($d / $minute) . " minutes ago";
130
+ //if less then 2 hours
131
+ if($d < $hour * 2) return "about 1 hour ago";
132
+ //if less then day
133
+ if($d < $day) return floor($d / $hour) . " hours ago";
134
+ //if more then day, but less then 2 days
135
+ if($d > $day && $d < $day * 2) return "yesterday";
136
+ //if less then year
137
+ if($d < $day * 365) return floor($d / $day) . " days ago";
138
+ //else return more than a year
139
+ return "over a year ago";
140
+ }
141
+ }
142
+
143
+
144
+ $tp_twitter_plugin_tweets = maybe_unserialize(get_option('tp_twitter_plugin_tweets'));
145
+ if(!empty($tp_twitter_plugin_tweets)){
146
+ print '
147
+ <div class="tp_recent_tweets">
148
+ <ul>';
149
+ $fctr = '1';
150
+ foreach($tp_twitter_plugin_tweets as $tweet){
151
+ print '<li><span>'.convert_links($tweet['text']).'</span><br /><a class="twitter_time" target="_blank" href="http://twitter.com/'.$instance['username'].'/statuses/'.$tweet['status_id'].'">'.relative_time($tweet['created_at']).'</a></li>';
152
+ if($fctr == $instance['tweetstoshow']){ break; }
153
+ $fctr++;
154
+ }
155
+
156
+ print '
157
+ </ul>
158
+ </div>';
159
+ }
160
+
161
+
162
+
163
+ echo $after_widget;
164
+ }
165
+
166
+
167
+ //save widget settings
168
+ public function update($new_instance, $old_instance) {
169
+ $instance = array();
170
+ $instance['title'] = strip_tags( $new_instance['title'] );
171
+ $instance['consumerkey'] = strip_tags( $new_instance['consumerkey'] );
172
+ $instance['consumersecret'] = strip_tags( $new_instance['consumersecret'] );
173
+ $instance['accesstoken'] = strip_tags( $new_instance['accesstoken'] );
174
+ $instance['accesstokensecret'] = strip_tags( $new_instance['accesstokensecret'] );
175
+ $instance['cachetime'] = strip_tags( $new_instance['cachetime'] );
176
+ $instance['username'] = strip_tags( $new_instance['username'] );
177
+ $instance['tweetstoshow'] = strip_tags( $new_instance['tweetstoshow'] );
178
+
179
+ if($old_instance['username'] != $new_instance['username']){
180
+ delete_option('tp_twitter_plugin_last_cache_time');
181
+ }
182
+
183
+ return $instance;
184
+ }
185
+
186
+
187
+ //widget settings form
188
+ public function form($instance) {
189
+ $defaults = array( 'title' => '', 'consumerkey' => '', 'consumersecret' => '', 'accesstoken' => '', 'accesstokensecret' => '', 'cachetime' => '', 'username' => '', 'tweetstoshow' => '' );
190
+ $instance = wp_parse_args( (array) $instance, $defaults );
191
+
192
+ echo '
193
+ <p><label>Title:</label>
194
+ <input type="text" name="'.$this->get_field_name( 'title' ).'" id="'.$this->get_field_id( 'title' ).'" value="'.esc_attr($instance['title']).'" class="widefat" /></p>
195
+ <p><label>Consumer Key:</label>
196
+ <input type="text" name="'.$this->get_field_name( 'consumerkey' ).'" id="'.$this->get_field_id( 'consumerkey' ).'" value="'.esc_attr($instance['consumerkey']).'" class="widefat" /></p>
197
+ <p><label>Consumer Secret:</label>
198
+ <input type="text" name="'.$this->get_field_name( 'consumersecret' ).'" id="'.$this->get_field_id( 'consumersecret' ).'" value="'.esc_attr($instance['consumersecret']).'" class="widefat" /></p>
199
+ <p><label>Access Token:</label>
200
+ <input type="text" name="'.$this->get_field_name( 'accesstoken' ).'" id="'.$this->get_field_id( 'accesstoken' ).'" value="'.esc_attr($instance['accesstoken']).'" class="widefat" /></p>
201
+ <p><label>Access Token Secret:</label>
202
+ <input type="text" name="'.$this->get_field_name( 'accesstokensecret' ).'" id="'.$this->get_field_id( 'accesstokensecret' ).'" value="'.esc_attr($instance['accesstokensecret']).'" class="widefat" /></p>
203
+ <p><label>Cache Tweets in every:</label>
204
+ <input type="text" name="'.$this->get_field_name( 'cachetime' ).'" id="'.$this->get_field_id( 'cachetime' ).'" value="'.esc_attr($instance['cachetime']).'" class="small-text" /> hours</p>
205
+ <p><label>Twitter Username:</label>
206
+ <input type="text" name="'.$this->get_field_name( 'username' ).'" id="'.$this->get_field_id( 'username' ).'" value="'.esc_attr($instance['username']).'" class="widefat" /></p>
207
+ <p><label>Tweets to display:</label>
208
+ <select type="text" name="'.$this->get_field_name( 'tweetstoshow' ).'" id="'.$this->get_field_id( 'tweetstoshow' ).'">';
209
+ $i = 1;
210
+ for(i; $i <= 10; $i++){
211
+ echo '<option value="'.$i.'"'; if($instance['tweetstoshow'] == $i){ echo ' selected="selected"'; } echo '>'.$i.'</option>';
212
+ }
213
+ echo '
214
+ </select></p>';
215
+ }
216
+ }
217
+
218
+
219
+ // register widget
220
+ function register_tp_twitter_widget(){
221
+ register_widget('tp_widget_recent_tweets');
222
+ }
223
+ add_action('init', 'register_tp_twitter_widget', 1)
224
+
225
+ ?>