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