forked from ryancramerdesign/MarkupTwitterFeed
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkupTwitterFeed.module
More file actions
495 lines (409 loc) · 15.4 KB
/
MarkupTwitterFeed.module
File metadata and controls
495 lines (409 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
<?php
class MarkupTwitterFeed extends WireData implements Module, ConfigurableModule, IteratorAggregate {
public static function getModuleInfo() {
return array(
'title' => 'Twitter Feed Markup',
'summary' => 'Module that generates a list (UL) for a Twitter feed. Usage: $t = new MarkupTwitterFeed(); echo $t->render(); or $t->render(array $options);',
'version' => 204,
'singular' => true,
'autoload' => false,
);
}
/**
* Optional items that may be specified as the first argument to the render() method
*
*/
protected $options = array(
'limit' => 3,
'cacheSeconds' => 600, // 10 minutes
'dateFormat' => "F j g:i a", // PHP date() or strftime() format, or "relative" to display relative time.
'linkUrls' => true,
'showHashTags' => true,
'showAtTags' => true,
'showDate' => 'after', // should be 'before', 'after', or blank to not show
'showReplies' => false, // set to true if you want replies included in the timeline
'showRetweets' => false, // set to true if you want retweets included in the timeline
'timeline' => 'user_timeline', // may be mentions_timeline, user_timeline, home_timeline or retweets_of_me
'screenName' => '', // optional: screen name to return results for. usually you would omit this.
'consumerKey' => '',
'consumerSecret' => '',
'userToken' => '',
'userSecret' => '',
'listOpen' => "\n<ul class='MarkupTwitterFeed'>",
'listClose' => "\n</ul>",
'listItemOpen' => "\n\t<li>",
'listItemClose' => "</li>",
'listItemText' => "{text}",
'listItemDate' => " <span class='date'>{date}</span>",
'listItemLink' => "<a rel='nofollow' href='{href}'>{url}</a>",
'listItemPhoto' => "<img src='{src}' title='{title}'>",
'listItemVideo' => "{video_tag}",
'listItemRetweetText' => "<i class='fa fa-retweet'></i> <span class='tweet-author'><img src='{author_icon_url}'>@{author}</span> <div class='tweet-text'>{text}</div>",
'videoAttributes' => "autoplay loop muted",
'preserveLineBreaks' => true,
);
/**
* Where cache files are stored
*
*/
protected $cachePath;
/**
* Define the cache path
*
* Should be done here in the construct rather than the init() because init() is not called on install/uninstall
*
*/
public function __construct() {
$this->cachePath = $this->config->paths->cache . $this->className() . '/';
$this->options['dateFormat'] = $this->_('F j g:i a'); // Translatable date format
}
/**
* Create a directory where we will store our cache files
*
*/
public function ___install() {
if(!$this->createCachePath()) throw new WireException("Unable to create directory: {$this->cachePath}");
}
/**
* Remove cache files and directory
*
*/
public function ___uninstall() {
if(is_dir($this->cachePath)) wireRmdir($this->cachePath, true);
}
protected function createCachePath() {
$path = $this->cachePath;
if(!is_dir($path)) if(!wireMkdir($path)) return false;
return true;
}
public function init() { }
/**
* Set a configuration option
*
* @param string $key Option name
* @param string|int $value Option value
* @return this
*
*/
public function set($key, $value) {
if($key == 'options' && is_array($value)) $this->options = array_merge($this->options, $value);
else if(array_key_exists($key, $this->options)) $this->options[$key] = $value;
else return parent::set($key, $value);
return $this;
}
/**
* Get a configuration option
*
* Note that this only returns defaults, and the values returned may not represent runtime changes.
*
*/
public function get($key) {
if(array_key_exists($key, $this->options)) return $this->options[$key];
return parent::get($key);
}
/**
* Retrieve JSON from Twitter
*
* @return string|bool JSON string on success, boolean false on error
*
*/
protected function getTwitterJSON(array $options) {
if(!class_exists('tmhOAuth', false)) {
require_once(wire('config')->paths->MarkupTwitterFeed . 'tmhOAuth/tmhOAuth.php');
}
$oAuth = new tmhOAuth(array(
'consumer_key' => $options['consumerKey'],
'consumer_secret' => $options['consumerSecret'],
'user_token' => $options['userToken'],
'user_secret' => $options['userSecret']
));
$params = array(
'exclude_replies' => !$options['showReplies'],
'include_rts' => $options['showRetweets'],
'trim_user' => ! $options['showRetweets'], // we need user details only for retweets
'tweet_mode' => 'extended',
);
if(!empty($options['screenName'])) $params['screen_name'] = $options['screenName'];
$code = $oAuth->request('GET', $oAuth->url("1.1/statuses/$options[timeline]", 'json'), $params);
if($code != 200) {
if(wire('log')) wire('log')->error($oAuth->response['response']); // 2.3.1+
$this->error(htmlentities($oAuth->response['response']), Notice::debug);
return false;
}
return $oAuth->response['response'];
}
/**
* Get array of Twitter data, whether from cache or from JSON feed
*
@ @param array $options
* @return bool|array Returns boolean false on failure, array of data on success.
*
*/
protected function getData(array $options) {
$options = array_merge($this->options, $options);
$cacheFile = $this->cachePath . md5(print_r($options, true)) . '.json.cache';
$saveCache = false;
$cacheFileExists = is_file($cacheFile);
$json = false;
if(!$cacheFileExists || time() - filemtime($cacheFile) > $options['cacheSeconds']) {
$json = $this->getTwitterJSON($options);
$saveCache = true;
}
if (($json === false) && $cacheFileExists) {
$json = file_get_contents($cacheFile);
}
if($json === false) return false;
$out = json_decode($json, true);
if($out && $saveCache) {
if(is_dir($this->cachePath)) wireRmdir($this->cachePath, true);
$this->createCachePath();
file_put_contents($cacheFile, $json, LOCK_EX);
}
return $out;
}
/**
* For IteratorAggregate interface
*
*/
public function getIterator() {
$data = $this->getData(array());
if ($data === false) $data = array();
return new ArrayObject($data);
}
/**
* Render a Twitter feed
*
* Returns markup of Twitter feed on success or error message string on error.
* For more error details, see your log file at /site/assets/logs/errors.txt
*
* @return string
*
*/
public function render($options = array(), $options2 = array()) {
if(is_string($options)) {
// throw away first argument which contains the old RSS URL, no longer used
$rssUrl = $options;
$options = $options2;
}
$out = '';
$error = $this->_('Error retrieving Twitter status');
$data = $this->getData($options);
$options = array_merge($this->options, $options);
if($data === false) {
$errorCode = json_last_error();
if(wire('log')) wire('log')->error("$error: $errorCode");
if(wire('config')->debug) $error .= ": " . $errorCode;
return $error;
} else if(!count($data)) {
return $this->_('Nothing to show');
}
$n = 0;
$out .= $options['listOpen'];
foreach($data as $item) {
$out .= $this->renderItem($item, $options);
if(++$n >= $options['limit']) break;
}
$out .= $options['listClose'];
return $out;
}
/**
* Render an individual tweet
*
*/
public function renderItem(array $item, array $options = array()) {
$options = array_merge($this->options, $options);
$isRetweet = isset($item['retweeted']) && $item['retweeted'];
if ($isRetweet and isset($item['retweeted_status'])) {
$item = $item['retweeted_status'];
}
$text = $item['full_text'] ?: $item['text'];
if(!$options['showHashTags']) $text = preg_replace('/\#([^\s]+|$)\s*/', '', $text);
if(!$options['showAtTags']) $text = preg_replace('/@([^\s]+|$)\s*/', '', $text);
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
$text = wire('sanitizer')->entities($text);
$text = $this->encodeEmojis($text);
if ($options['preserveLineBreaks'] === true) {
$text = str_replace("\n", '<br>', $text);
}
elseif ($options['preserveLineBreaks'] === 'coalesce') {
$text = preg_replace('/\n+/', '<br>', $text);
}
foreach($item['entities']['urls'] as $u) {
if($options['linkUrls']) {
$linkHtml = str_replace(['{href}', '{url}'], [wire('sanitizer')->entities($u['expanded_url']), $u['display_url']], $options['listItemLink']);
$text = preg_replace('!' . preg_quote($u['url'], '!') . '(\b|$)!i', $linkHtml, $text);
} else {
$text = preg_replace('!' . preg_quote($u['url'], '!') . '(\b|$)!i', $u['display_url'], $text);
}
}
if (isset($item['extended_entities']) && isset($item['extended_entities']['media'])) {
$mediaUrlField = wire('config')->https ? 'media_url_https' : 'media_url';
foreach($item['extended_entities']['media'] as $m) {
if (($m['type'] == 'photo') && $options['listItemPhoto'])
{
$photoHtml = str_replace(array('{src}', '{title}'),
array(wire('sanitizer')->entities($m[$mediaUrlField]), wire('sanitizer')->entities($m['display_url'])),
$options['listItemPhoto']);
$text = preg_replace('!' . preg_quote($m['url'], '!') . '(\b|$)!i', $photoHtml, $text);
}
elseif (($m['type'] == 'video') && $options['listItemVideo']) {
$posterUrl = wire('sanitizer')->entities($m[$mediaUrlField]);
// Get the aspect ratio
$aspectRatioArray = $m['video_info']['aspect_ratio'];
if (! $aspectRatioArray) $aspectRatioArray = [16, 9];
$aspectRatio = intval($aspectRatioArray[1] / $aspectRatioArray[0] * 1000) / 10;
// get the video sources
$videoSourcesHtml = "";
$videoSources = array();
foreach ($m['video_info']['variants'] as $variant) {
$contentType = wire('sanitizer')->entities($variant['content_type']);
if (! isset($variant['bitrate'])) {
// adaptative streming format: put first in video sources
$contentUrl = wire('sanitizer')->entities($variant['url']);
$videoSourcesHtml .= "<source src='$contentUrl' type='$contentType'>";
}
else {
// Fixed bitrate: select the highest quality (!)
if (! isset($videoSources[$contentType]) || ($videoSources[$contentType]['bitrate'] < $variant['bitrate'])) {
$videoSources[$contentType] = $variant;
}
}
}
foreach ($videoSources as $contentType => $variant) {
$contentUrl = wire('sanitizer')->entities($variant['url']);
$videoSourcesHtml .= "<source src='$contentUrl' type='$contentType'>";
}
$videoAttributes = 'controls';
if (isset($options['videoAttributes'])) {
$videoAttributes .= ' ' . $options['videoAttributes'];
}
$videoDivHtml = <<<"VIDEO_MEDIA_HTML"
<div class='html-video-box'>
<div class='padding' style='padding-top:{$aspectRatio}%;'></div>
<video {$videoAttributes} poster='$posterUrl'>
{$videoSourcesHtml}
<div class='html-video-fallback'>
<img src='{$posterUrl}' alt='This video can not be played in your web browser...'>
</div>
</video>
</div>
VIDEO_MEDIA_HTML;
$videoHtml = str_replace('{video_tag}', $videoDivHtml, $options['listItemVideo']);
$text = preg_replace('!' . preg_quote($m['url'], '!') . '(\b|$)!i', $videoHtml, $text);
}
else {
// Hide the media URL
$text = preg_replace('!' . preg_quote($m['url'], '!') . '(\b|$)!i', '', $text);
}
}
}
elseif (isset($item['entities']) && isset($item['entities']['media'])) {
$mediaUrlField = wire('config')->https ? 'media_url_https' : 'media_url';
foreach($item['entities']['media'] as $m) {
if($options['listItemPhoto']) {
$photoHtml = str_replace(array('{src}', '{title}'),
array(wire('sanitizer')->entities($m[$mediaUrlField]), wire('sanitizer')->entities($m['display_url'])),
$options['listItemPhoto']);
$text = preg_replace('!' . preg_quote($m['url'], '!') . '(\b|$)!i', $photoHtml, $text);
} else {
// Hide the media URL
$text = preg_replace('!' . preg_quote($m['url'], '!') . '(\b|$)!i', '', $text);
}
}
}
if($options['showDate']) {
$date = strtotime($item['created_at']);
if($options['dateFormat'] == 'relative') $date = wireRelativeTimeStr($date);
else if(strpos($options['dateFormat'], '%') !== false) $date = strftime($options['dateFormat'], $date);
else $date = date($options['dateFormat'], $date);
$dateOut = str_replace('{date}', $date, $options['listItemDate']);
} else $dateOut = '';
$out = $options['listItemOpen'];
if(strpos($options['showDate'], 'before') !== false) {
$out .= $dateOut;
}
if (!$isRetweet) {
$out .= str_replace('{text}', $text, $options['listItemText']);
}
else {
$tweetAuthorScreenName = $item['user']['screen_name'];
$tweetAuthorImageUrl = $item['user']['profile_image_url_https'];
$out .= str_replace(array('{text}', '{author}', '{author_icon_url}'), array($text, $tweetAuthorScreenName, $tweetAuthorImageUrl), $options['listItemRetweetText']);
}
if(strpos($options['showDate'], 'after') !== false) {
$out .= $dateOut;
}
$out .= $options['listItemClose'];
return $out;
}
/**
* Html-encode emojis in the item text
* (origin: http://wp-a2z.com/oik_api/wp_encode_emoji/)
*
*/
private function encodeEmojis( $content ) {
if ( function_exists( 'mb_convert_encoding' ) ) {
$regex = '/(
\x23\xE2\x83\xA3 # Digits
[\x30-\x39]\xE2\x83\xA3
| \xF0\x9F[\x85-\x88][\xA6-\xBF] # Enclosed characters
| \xF0\x9F[\x8C-\x97][\x80-\xBF] # Misc
| \xF0\x9F\x98[\x80-\xBF] # Smilies
| \xF0\x9F\x99[\x80-\x8F]
| \xF0\x9F\x9A[\x80-\xBF] # Transport and map symbols
)/x';
$matches = array();
if ( preg_match_all( $regex, $content, $matches ) ) {
if ( ! empty( $matches[1] ) ) {
foreach( $matches[1] as $emoji ) {
/*
* UTF-32's hex encoding is the same as HTML's hex encoding.
* So, by converting the emoji from UTF-8 to UTF-32, we magically
* get the correct hex encoding.
*/
$unpacked = unpack( 'H*', mb_convert_encoding( $emoji, 'UTF-32', 'UTF-8' ) );
if ( isset( $unpacked[1] ) ) {
$entity = '&#x' . ltrim( $unpacked[1], '0' ) . ';';
$content = str_replace( $emoji, $entity, $content );
}
}
}
}
}
return $content;
}
/**
* Configure the module
*
*/
public static function getModuleConfigInputfields(array $data) {
$wrap = new InputfieldWrapper();
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Twitter API Settings');
$form->notes = __('You may obtain the above pieces of information by creating a Twitter application at [https://dev.twitter.com/apps](https://dev.twitter.com/apps).');
$items = array(
'consumerKey' => __('Consumer Key'),
'consumerSecret' => __('Consumer Secret'),
'userToken' => __('Access Token'),
'userSecret' => __('Access Secret'),
);
foreach($items as $name => $label) {
$f = wire('modules')->get('InputfieldText');
$f->attr('name', $name);
$f->label = $label;
$f->required = true;
$f->columnWidth = 50;
if(isset($data[$name])) $f->attr('value', $data[$name]);
$form->add($f);
}
$wrap->add($form);
$f = wire('modules')->get('InputfieldInteger');
$f->attr('name', 'cacheSeconds');
$f->label = __('How often to check for new tweets');
$f->description = __('Enter the number of seconds.');
$f->notes = __('Examples: 60=1 minute, 600=10 minutes, 3600=1 hour, 14400=4 hours, 86500=1 day.');
$f->attr('value', isset($data['cacheSeconds']) ? (int) $data['cacheSeconds'] : 600);
$wrap->add($f);
return $wrap;
}
}