/
arc_twitter_v2.php
2349 lines (1990 loc) · 79.2 KB
/
arc_twitter_v2.php
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
$plugin['name'] = 'arc_twitter';
$plugin['version'] = '2.0alpha-01';
$plugin['author'] = 'Andy Carter';
$plugin['author_uri'] = 'http://www.redhotchilliproject.com/';
$plugin['description'] = '<a href="http://www.twitter.com">Twitter</a> for Textpattern';
$plugin['order'] = '5';
// Plugin 'type' defines where the plugin is loaded
// 0 = public : only on the public side of the website (default)
// 1 = public+admin : on both the public and admin side
// 2 = library : only when include_plugin() or require_plugin() is called
// 3 = admin : only on the admin side
$plugin['type'] = '1';
// Plugin "flags" signal the presence of optional capabilities to the core plugin loader.
// Use an appropriately OR-ed combination of these flags.
// The four high-order bits 0xf000 are available for this plugin's private use
if (!defined('PLUGIN_HAS_PREFS')) define('PLUGIN_HAS_PREFS', 0x0001); // This plugin wants to receive "plugin_prefs.{$plugin['name']}" events
if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events
$plugin['flags'] = '3';
if (!defined('txpinterface'))
@include_once('zem_tpl.php');
# --- BEGIN PLUGIN CODE ---
global $prefs,$txpcfg,$arc_twitter_consumerKey,$arc_twitter_consumerSecret;
$arc_twitter = array();
$arc_twitter_consumerKey = 'nKcXslwzZhBd0kfKMetnPA';
$arc_twitter_consumerSecret = 'C6nSPCL3eeHGTBhKCgwd9oclcuD0srB8WVkfXQYC54';
add_privs('plugin_prefs.arc_twitter','1,2');
register_callback('arc_twitter_install','plugin_lifecycle.arc_twitter', 'installed');
register_callback('arc_twitter_uninstall','plugin_lifecycle.arc_twitter', 'deleted');
register_callback('arc_twitter_prefs','plugin_prefs.arc_twitter');
if (!isset($prefs['arc_twitter_user']))
set_pref('arc_twitter_user', '', 'arc_twitter', 1, 'text_input');
if (!isset($prefs['arc_twitter_prefix']))
set_pref('arc_twitter_prefix','Just posted:', 'arc_twitter', 2, 'text_input');
if (!isset($prefs['arc_twitter_cache_dir']))
set_pref('arc_twitter_cache_dir',$txpcfg['txpath'].$prefs['tempdir'], 'arc_twitter', 1, 'text_input');
if (!isset($prefs['arc_twitter_tweet_default']))
set_pref('arc_twitter_tweet_default', 1, 'arc_twitter', 2, 'yesnoRadio');
if (!isset($prefs['arc_twitter_url_method']))
set_pref('arc_twitter_url_method', 'tinyurl', 'arc_twitter', 2,
'arc_twitter_url_method_select');
// Make sure that the Twitter tab has been defined
if (!isset($prefs['arc_twitter_tab'])) {
set_pref('arc_twitter_tab', 'extensions', 'arc_twitter', 2,
'arc_twitter_tab_select');
$prefs['arc_twitter_tab'] = 'extensions';
}
if (@txpinterface == 'admin') {
if (!empty($prefs['arc_twitter_user'])
&& !empty($prefs['arc_twitter_accessToken'])
&& !empty($prefs['arc_twitter_accessTokenSecret']) ) {
if ($prefs['arc_twitter_tab']) {
add_privs('arc_admin_twitter', '1,2,3,4');
register_tab($prefs['arc_twitter_tab'], 'arc_admin_twitter', 'Twitter');
register_callback('arc_admin_twitter', 'arc_admin_twitter');
}
register_callback('arc_article_tweet', 'ping');
register_callback('arc_article_tweet', 'article', 'edit', 1);
register_callback('arc_append_twitter', 'article_ui', 'status');
}
}
/*
Public-side functions
================================================================
*/
function arc_twitter($atts)
{
global $prefs,$arc_twitter_consumerKey, $arc_twitter_consumerSecret;
extract(lAtts(array(
'user' => $prefs['arc_twitter_user'],
'password' => '',
'timeline' => 'user',
'limit' => '10',
'retweets' => false,
'dateformat'=> $prefs['archive_dateformat'],
'caching' => '1',
'cache_dir' => $prefs['arc_twitter_cache_dir'],
'cache_time'=> '5',
'label' => '',
'labeltag' => '',
'break' => 'li',
'wraptag' => '',
'class' => __FUNCTION__,
'class_posted' => __FUNCTION__.'-posted'
),$atts));
$twit = new arc_Twitter($arc_twitter_consumerKey, $arc_twitter_consumerSecret);
if ($caching) { // turn on caching, recommended (default)
$twit->setCaching(true);
$twit->cacheDir($cache_dir);
$twit->cacheTime($cache_time);
} else { // turn off caching, not recommended other than for testing
$twit->setCaching(false);
}
switch ($timeline) {
case 'home': case 'friends':
$timeline = 'statuses/friends_timeline'; break;
case 'mentions':
$timeline = 'statuses/mentions'; break;
case 'user': default: $timeline = 'statuses/user_timeline';
}
$out = array();
$xml = $twit->get($timeline
, array('screen_name'=>$user,'count'=>$limit,'include_rts'=>$retweets));
if ($xml) {
$tweets = @$xml->xpath('/statuses/status');
if ($tweets) foreach ($tweets as $tweet) {
$time = strtotime(htmlentities($tweet->created_at));
$date = safe_strftime($dateformat,$time);
$out[] = arc_Twitter::makeLinks(htmlentities($tweet->text, ENT_QUOTES,'UTF-8'))
.' '.tag(htmlentities($date),'span',' class="'.$class_posted.'"');
}
return doLabel($label, $labeltag).doWrap($out, $wraptag, $break, $class);
}
}
function arc_twitter_search($atts)
{
global $prefs,$arc_twitter_consumerKey, $arc_twitter_consumerSecret;
extract(lAtts(array(
'user' => $prefs['arc_twitter_user'],
'search' => '',
'hashtags' => '',
'user' => '',
'reply' => '',
'mention' => '',
'limit' => '10',
'lang' => '',
'dateformat'=> $prefs['archive_dateformat'],
'caching' => '1',
'cache_dir' => $prefs['arc_twitter_cache_dir'],
'cache_time'=> '5',
'label' => '',
'labeltag' => '',
'break' => 'li',
'wraptag' => '',
'class' => __FUNCTION__,
'class_posted' => __FUNCTION__.'-posted',
'class_user' => __FUNCTION__.'-user'
),$atts));
$twit = new arc_Twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret);
if ($caching) { // turn on caching, recommended (default)
$twit->setCaching(true);
$twit->cacheDir($cache_dir);
$twit->cacheTime($cache_time);
} else { // turn off caching, not recommended other than for testing
$twit->setCaching(false);
}
// construct search query
if (!empty($search)) {
$terms = explode(',',$search); $terms = array_map('trim',$terms);
$search = implode(' ',$terms);
}
if ($hashtags) {
$hashes = explode(',',$hashtags); $hashes = array_map('trim',$hashes);
$search.= (($search)?' ':'').'#'.implode(' #',$hashes);
}
if ($reply) {
$search.= (($search)?' ':'').'to:'.trim($reply);
}
if ($user) {
$search.= (($search)?' ':'').'from:'.trim($user);
}
if ($mention) {
$search.= (($search)?' ':'').'@'.trim($mention);
}
if (empty($search)) {
return '';
} else {
$search = urlencode($search);
}
$out = array();
$tweets = $twit->get('http://search.twitter.com/search.atom?q='.$search
, array('rpp'=>$limit,'lang'=>$lang));
if ($tweets) { foreach ($tweets->entry as $tweet) {
preg_match("/(.*) \((.*)\)/",$tweet->author->name,$matches);
list($author,$uname,$name) = $matches;
$time = strtotime(htmlentities($tweet->published));
$date = safe_strftime($dateformat,$time);
$text = $tweet->title;
$out[] = tag(href(htmlentities($uname),$tweet->author->uri,
' title="'.htmlentities($name).'"').': ','span'
,' class="'.$class_user.'"')
.arc_Twitter::makeLinks(htmlentities($text, ENT_QUOTES,'UTF-8'))
.' '.tag(htmlentities($date),'span'
,' class="'.$class_posted.'"');
} return doLabel($label, $labeltag)
.doWrap($out, $wraptag, $break, $class); }
}
function arc_twitter_tweet($atts) {
global $thisarticle;
extract(lAtts(array(
'id' => $thisarticle['thisid'],
'include_url' => true
),$atts));
if ($id) {
// Fetch arc_twitter stuff to build tweet from
$tweet = ($include_url) ? safe_row("tweet", 'arc_twitter', "article_id={$id}")
: safe_row("REPLACE(tweet,CONCAT(' ',tinyurl),'') AS tweet"
, 'arc_twitter', "article_id={$id}");
}
if ($tweet['tweet']) {
return arc_Twitter::makeLinks(
htmlentities($tweet['tweet'], ENT_QUOTES,'UTF-8'));
}
}
function arc_twitter_tweet_url($atts, $thing=null) {
global $thisarticle,$prefs;
extract(lAtts(array(
'id' => $thisarticle['thisid'],
'title' => '',
'class' => ''
),$atts));
if ($id) {
// Fetch arc_twitter stuff to build tweet from
$tweet = safe_row("tweet_id"
, 'arc_twitter', "article_id={$id}");
}
if ($tweet['tweet_id']) {
$url = "http://twitter.com/".$prefs['arc_twitter_user']."/status/".$tweet['tweet_id'];
if ($thing===null) {
return $url;
}
return href(parse($thing), $url,
($title ? ' title="'.$title.'"' : '')
.($class ? ' class="'.$class.'"' : ''));
}
}
function arc_twitter_tinyurl($atts, $thing=null) {
global $thisarticle;
extract(lAtts(array(
'id' => $thisarticle['thisid'],
'title' => '',
'class' => ''
),$atts));
if ($id) {
// Fetch arc_twitter stuff to build tweet from
$tweet = safe_row("tinyurl"
, 'arc_twitter', "article_id={$id}");
}
if ($tweet['tinyurl']) {
if ($thing===null) {
return $tweet['tinyurl'];
}
return href(parse($thing), $tweet['tinyurl'],
($title ? ' title="'.$title.'"' : '')
.($class ? ' class="'.$class.'"' : ''));
}
}
function arc_twitter_retweet($atts, $thing=null)
{
global $prefs,$arc_twitter_consumerKey, $arc_twitter_consumerSecret;
global $thisarticle;
extract(lAtts(array(
'user' => $prefs['arc_twitter_user'], // via user account
'url' => '',
'text' => '',
'follow1' => '',
'follow2' => '',
'lang' => '',
'count' => 'horizontal',
'include_js'=> true,
'wraptag' => '',
'class' => 'twitter-share-button'
),$atts));
$q = ''; // query string
if ($id=$thisarticle['thisid']) {
// Fetch arc_twitter stuff to build tweet from
$row = safe_row("REPLACE(tweet,CONCAT(' ',tinyurl),'') AS tweet,tinyurl"
, 'arc_twitter', "article_id={$id}");
if ($url=='') {
$url = ($url) ? $url : permlinkurl($thisarticle);
$q = 'url='.urlencode($url);
}
if ($text=='') {
$text = ($row['tweet']) ? $row['tweet'] : $thisarticle['title'];
}
$q .= ($q ? '&' : '').'text='.urlencode($text);
}
if ($user) {
$q .= ($q ? '&' : '').'via='.urlencode($user);
}
if ($follow1&&$follow2) {
$q .= ($q ? '&' : '').'related='.urlencode($follow1.':'.$follow2);
} elseif ($follow1||$follow2) {
$q .= ($q ? '&' : '').'related='.urlencode($follow1.$follow2);
}
switch ($lang) {
case 'fr': break; case 'de': break; case 'es': break; case 'jp': break;
default:
$lang = 'en';
}
$q .= ($q ? '&' : '').'lang='.urlencode($lang);
switch ($count) {
case 'none': break; case 'vertical': break;
default:
$count = 'horizontal';
}
$q .= ($q ? '&' : '').'count='.urlencode($count);
$thing = ($thing===null) ? 'Tweet' : parse($thing);
$html = href($thing,'http://twitter.com/share?'.$q
, ' class="'.$class.'"');
$js = ($include_js) ?
'<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>'
: '';
return $js.$html;
}
/*
Admin-side functions
================================================================
*/
// Installation function - builds MySQL table
function arc_twitter_install()
{
// For first install, create table for tweets
$sql = "CREATE TABLE IF NOT EXISTS ".PFX."arc_twitter ";
$sql.= "(arc_twitterid INTEGER AUTO_INCREMENT PRIMARY KEY,
article_id INTEGER(11),
tweet_id BIGINT(20),
tweet VARCHAR(140),
tinyurl VARCHAR(30));";
if (!safe_query($sql)) {
return 'Error - unable to create arc_twitter table';
}
}
// Uninstall function - deletes MySQL table and related preferences
function arc_twitter_uninstall()
{
$sql = "DROP TABLE IF EXISTS ".PFX."arc_twitter;";
if (!safe_query($sql)) {
return 'Error - unable to delete arc_twitter table';
}
$sql = "DELETE FROM ".PFX."txp_prefs WHERE event='arc_twitter';";
if (!safe_query($sql)) {
return 'Error - unable to delete arc_twitter preferences';
}
}
function arc_twitter_url_method_select($name, $val)
{
$methods = array('tinyurl' => 'Tinyurl', 'isgd' => 'Is.gd', 'smd' => 'smd_short_url');
return selectInput($name, $methods, $val);
}
function arc_twitter_tab_select($name, $val)
{
$tabs = array('content' => 'Content',
'extensions' => 'Extensions',
'' => 'Hidden');
return selectInput($name, $tabs, $val);
}
// Provide interface for setting preferences
function arc_twitter_prefs($event,$step)
{
global $prefs,$arc_twitter_consumerKey,$arc_twitter_consumerSecret;
$user = $prefs['arc_twitter_user'];
$prefix = $prefs['arc_twitter_prefix'];
$tweet_default = $prefs['arc_twitter_tweet_default'];
$url_method = $prefs['arc_twitter_url_method'];
$cache_dir = $prefs['arc_twitter_cache_dir'];
$tab = $prefs['arc_twitter_tab'];
switch ($step) {
case 'prefs_save': pagetop('TXP Tweet', 'Preferences saved'); break;
case 'register': pagetop('TXP Tweet','Connect to Twitter'); break;
case 'validate':
default: pagetop('TXP Tweet');
}
$html = '';
if ($step=='register') { // OAuth registration process
$twit = new arc_twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret);
// Build a callback URL for Twitter to return to the next stage
$callbackURL = $twit->callbackURL($event,'validate');
$request = $twit->getRequestToken($callbackURL);
$request_token = $request["oauth_token"];
$request_token_secret = $request["oauth_token_secret"];
set_pref('arc_twitter_requestToken',$request_token
, 'arc_twitter',2);
set_pref('arc_twitter_requestTokenSecret',$request_token_secret
, 'arc_twitter',2);
$html.= startTable('edit').
tr(td(
('<p>'.href('Sign-in to Twitter'
,$twit->getAuthorizeURL($request))
.' and follow the instructions to allow TXP Tweet to use your account. If you are already signed in to Twitter then that account will be associated with TXP Tweet so you may need to sign out first if you want to use a different account.</p>')
)).endTable();
} elseif ($step=='validate') {
$twit = new arc_twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret, $prefs['arc_twitter_requestToken']
, $prefs['arc_twitter_requestTokenSecret']);
// Ask Twitter for an access token (and an access token secret)
$request = $twit->getAccessToken( gps('oauth_verifier') );
$access_token = $request['oauth_token'];
$access_token_secret = $request['oauth_token_secret'];
$user = $request['screen_name'];
// Store the access token and secret
set_pref('arc_twitter_accessToken',$access_token, 'arc_twitter',2);
set_pref('arc_twitter_accessTokenSecret',$access_token_secret
, 'arc_twitter',2);
set_pref('arc_twitter_user',$user);
$prefs['arc_twitter_accessToken'] = $access_token;
$prefs['arc_twitter_accessTokenSecret'] = $access_token_secret;
unset($twit);
}
if ($step=="prefs_save") {
$prefix = trim(gps('arc_twitter_prefix'));
$tweet_default = gps('arc_twitter_tweet_default');
$url_method = gps('arc_twitter_url_method');
$cache_dir = gps('arc_twitter_cache_dir');
$tab = gps('arc_twitter_tab');
if (strlen($prefix)<=20) {
set_pref('arc_twitter_prefix',$prefix);
} else {
$prefix = $prefs['arc_twitter_prefix'];
}
$tweet_default = ($tweet_default) ? 1 : 0;
set_pref('arc_twitter_tweet_default',$tweet_default);
set_pref('arc_twitter_url_method',$url_method);
set_pref('arc_twitter_cache_dir',$cache_dir);
set_pref('arc_twitter_tab',$tab);
}
if ( $step!='register' ) {
if ( isset($prefs['arc_twitter_accessToken'])
&& isset($prefs['arc_twitter_accessTokenSecret']) ) {
$twit = new arc_twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret, $prefs['arc_twitter_accessToken']
, $prefs['arc_twitter_accessTokenSecret']);
$registerURL = $twit->callbackURL($event,'register');
$html.= startTable('list').form(
tr(
tdcs(hed('Twitter account details', 2),2)
)
.tr(
tda('<label for="arc_twitter_user">Twitter username</label>',
' style="text-align: right; vertical-align: middle;"')
.td(
($prefs['arc_twitter_user']) ?
$user.' ('.href('Re-connect',$registerURL).')'
: '<em>unknown</em>'
.href('Connect to Twitter',$registerURL))
)
.tr(
tdcs(hed('Tweet settings', 2),2)
)
.tr(
tda('<label for="arc_twitter_cache_dir">Tweet prefix</label>',
' style="text-align: right; vertical-align: middle;"')
.td(fInput('text','arc_twitter_prefix',$prefix,'','','','','','arc_twitter_prefix'))
).tr(
tda('<label for="arc_twitter_tweet_default">Tweet articles by default</label>',
' style="text-align: right; vertical-align: middle;"')
.td(yesnoRadio('arc_twitter_tweet_default', $tweet_default, '', 'arc_twitter_tweet_default'))
).tr(
tda('<label for="arc_twitter_url_method">URL shortner</label>',
' style="text-align: right; vertical-align: middle;"')
.td(arc_twitter_url_method_select('arc_twitter_url_method',$url_method))
).tr(
tdcs(hed('Twitter tab', 2),2)
).tr(
tda('<label for="arc_twitter_tab">Location of Twitter tab</label>',
' style="text-align: right; vertical-align: middle;"')
.td(arc_twitter_tab_select('arc_twitter_tab',$tab))
).tr(
tdcs(hed('Cache', 2),2)
)
.tr(
tda('<label for="arc_twitter_cache_dir">Cache directory</label>',
' style="text-align: right; vertical-align: middle;"')
.td(fInput('text','arc_twitter_cache_dir',$cache_dir,'','','','','','arc_twitter_cache_dir'))
)
.tr(
tda(
fInput('submit', 'Submit', gTxt('save_button'), 'publish')
.n.sInput('prefs_save')
.n.eInput('plugin_prefs.arc_twitter')
, ' colspan="2" class="noline"')))
.endTable();
} elseif ( $step!='register' ) {
$registerURL = arc_twitter::callbackURL($event,'register');
$html.= startTable('list').form(
tr(
tdcs(hed('Twitter account details', 2),2)
)
.tr(
tda('<label for="arc_twitter_user">Twitter username</label>',
' style="text-align: right; vertical-align: middle;"')
.td(
('<em>unknown</em> ('
.href('Connect to Twitter',$registerURL).')')
)))
.endTable();
}
}
echo $html;
}
// Add Twitter tab to Textpattern
function arc_admin_twitter($event,$step)
{
global $prefs, $arc_twitter_consumerKey, $arc_twitter_consumerSecret;
$twit = new arc_twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret, $prefs['arc_twitter_accessToken']
, $prefs['arc_twitter_accessTokenSecret']);
$twit->cacheDir($prefs['arc_twitter_cache_dir']);
$xml = $twit->get('users/show'
, array('screen_name'=>$prefs['arc_twitter_user']));
$twitterUser = @$xml->xpath('/user');
$twitterUser = $twitterUser[0];
$twitterUserURL = 'http://www.twitter.com/'.$twitterUser->screen_name;
if ($step=="tweet") { // post an update to Twitter
// fetch and clean message
$message = strip_tags(gps('message'));
$count = strlen($message);
if ($count<=140 && $count>0) { // post update
$result = $twit->post('statuses/update', array('status' => $message));
} else { // message too long, JavaScript interface should prevent this
$result = false;
}
pagetop('Twitter',
(($result!=false)?'Twitter updated':'Error updating Twitter'));
} elseif ($step=="delete") { // delete an update from Twitter
$id = strip_tags(gps('id'));
if ($id) {
$twit->delete('statuses/destroy'.$id);
safe_delete('arc_twitter',"tweet_id = $id");
}
pagetop('Twitter','Twitter updated');
} else {
pagetop('Twitter');
}
// Prepare JavaScript to create Twitter update interface
$js = '<script language="javascript" type="text/javascript">';
$js.= "$(document).ready(function(){
var counterStyle = 'font-weight:bold;float:right;font-size:2em;line-height:1.2em;';
$('#tweetcount').attr('style', counterStyle+'color:#ccc;');
$('#message').keyup(function() {
var count = 140-$('#message').val().length;
$('#tweetcount').html(count+''); // hack to force output of 0
if (count<0) {
$('input.publish').attr('disabled', 'disabled');
} else {
$('input.publish').attr('disabled', '');
}
if (count<0) {
$('#tweetcount').attr('style', counterStyle+'color:#f00;');
} else if (count<10) {
$('#tweetcount').attr('style', counterStyle+'color:#000;');
} else {
$('#tweetcount').attr('style', counterStyle+'color:#ccc;');
}
})
});";
$js.= "</script>";
$out = '';
$xml = $twit->get('statuses/user_timeline'
, array('screen_name'=>$prefs['arc_twitter_user'],'count'=>25));
$tweets = @$xml->xpath('/statuses/status');
if ($tweets) foreach ($tweets as $tweet) {
$time = strtotime(htmlentities($tweet->created_at));
$date = safe_strftime($prefs['archive_dateformat'],$time);
$out.= tr(td($date,'span')
.td(arc_Twitter::makeLinks(htmlentities($tweet->text
, ENT_QUOTES,'UTF-8')))
.td(dLink('arc_admin_twitter','delete','id',$tweet->id,''))
);
}
$html = startTable('edit')
.tr(td(
graf('<img src="'.$twitterUser->profile_image_url.'" alt="Twitter avatar" />'
,' style="float:left;padding:2px;"')
.graf(href($twitterUser->name,$twitterUserURL),' style="font-size:1.2em;font-weight:bold;"')
.graf(href($twitterUser->friends_count.' following',$twitterUserURL.'/following')
.', '.href($twitterUser->followers_count.' followers',$twitterUserURL.'/followers')
.', '.href($twitterUser->statuses_count.' updates',$twitterUserURL))))
.tr(td(form(
graf("Update Twitter...<span id='tweetcount' style='font-weight:bold;float:right;'>140</span>")
.text_area('message','50','550','','message')
.eInput('arc_admin_twitter')
.sInput('tweet').br
.fInput('submit','update',gTxt('Update'),'publish')
)))
.endTable();
// Attach recent Twitter updates
$html.= startTable('list','','','','90%')
.$out
.endTable();
// Output JavaScript and HTML
echo $js.$html;
}
// Add Twitter options to article article screen
function arc_append_twitter($event, $step, $data, $rs1)
{
global $prefs, $arc_twitter;
$prefix = trim(gps('arc_twitter_prefix'));
$prefix = ($prefix) ? $prefix : $prefs['arc_twitter_prefix'];
$suffix = trim(gps('arc_twitter_suffix'));
if ($rs1['ID']) {
$sql = "SELECT tweet_id,tweet FROM ".PFX."arc_twitter WHERE article_id=".$rs1['ID'].";";
$rs2 = safe_query($sql); $rs2 = nextRow($rs2);
} else { // new article
$rs2 = '';
}
if ($rs1['ID'] && $rs2['tweet_id']) {
$content = arc_Twitter::makeLinks($rs2['tweet']);
return $data.fieldset($content, 'Twitter update', 'arc_twitter');
} else {
$var = ($rs1['ID']) ? 0 : $prefs['arc_twitter_tweet_default'];
$content = yesnoRadio('arc_tweet_this', $var, '', 'arc_tweet_this');
$content .= tag(href('Options','#arc_twitter_options'),'p',' class="plain lever" style="margin-top:5px;"');
$content .= tag(tag('Tweet prefix','label', ' for="arc_twitter_prefix"')
.fInput('text','arc_twitter_prefix',$prefix,'edit','','','22','','arc_twitter_prefix')
.tag('Tweet suffix (eg #hashtags)','label', ' for="arc_twitter_suffix"')
.fInput('text','arc_twitter_suffix',$suffix,'edit','','','22','','arc_twitter_suffix')
,'div',' id="arc_twitter_options" class="toggle" style="display:none"');
if (isset($arc_twitter['error'])) {
$content .= '<p>'.$arc_twitter['error'].'</p>';
}
return $data.fieldset($content, 'Update Twitter', 'arc_twitter');
}
}
// Update Twitter with posted article
function arc_article_tweet($event,$step)
{
global $prefs, $arc_twitter, $arc_twitter_consumerKey
, $arc_twitter_consumerSecret;
$article_id = empty($GLOBALS['ID']) ? gps('ID') : $GLOBALS['ID'];
if (!empty($article_id)) {
include_once txpath.'/publish/taghandlers.php';
$article = safe_row("ID, Title, Section, Posted", 'textpattern',
"ID={$article_id} AND Status=4 AND now()>=Posted");
if ($article && gps('arc_tweet_this')) { // tweet article
// Make short URL
$url = permlinkurl($article);
$short_url = arc_shorten_url($url,$prefs['arc_twitter_url_method'],
array('id'=>$article_id));
if (!$short_url) { // Failed to obtain a shortened URL, do not tweet!
$arc_twitter['error'] = 'Unable to obtain a short URL for this article.';
return false;
}
// Construct Twitter update
$prefix = trim(gps('arc_twitter_prefix'));
$pre_len = strlen($prefix);
$prefix = ($prefix && $pre_len<=20) ? $prefix.' ' : '';
$suffix = trim(gps('arc_twitter_suffix'));
$suf_len = strlen($suffix);
$suffix = ($suffix && $suf_len<=40) ? ' '.$suffix : '';
$url_len = strlen($short_url)+1; // count URL length + 1 for prefixed space
if ($prefix) $pre_len += 1;
if ($suffix) $suf_len += 1;
if ((strlen($article['Title'])+$url_len+$pre_len+$suf_len)>140) {
$article['Title'] = substr($article['Title'],0,135-$url_len-$pre_len-$suf_len).'...';
}
$tweet = $prefix.$article['Title']." ".$short_url.$suffix;
// Update Twitter
$twit = new arc_twitter($arc_twitter_consumerKey
, $arc_twitter_consumerSecret, $prefs['arc_twitter_accessToken']
, $prefs['arc_twitter_accessTokenSecret']);
$result = $twit->post('statuses/update', array('status' => $tweet));
$tweet_id = (is_object($result)) ? $result[0]->id : 0;
if ($tweet_id) {
$tweet = addslashes($tweet);
// update arc_twitter table with tweet
$sql = "INSERT INTO ".PFX."arc_twitter (article_id,tweet_id,tweet,tinyurl) ";
$sql.= "VALUES($article_id,$tweet_id,\"$tweet\",'$short_url');";
safe_query($sql);
return true;
} else {
$arc_twitter['error'] = 'Twitter response: '
.$twit->http_code;
return false;
}
}
}
return false;
}
/*
* Shorten URLs using various methods
*/
function arc_shorten_url($url, $method='', $atts=array())
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
switch ($method) {
case 'smd': // create a shortened URL using SMD Short URL
return ($atts['id']) ? hu.$atts['id'] : false; break;
case 'isgd':
$u = 'http://is.gd/api.php?longurl='.urlencode($url);
curl_setopt($ch, CURLOPT_URL, $u);
$tinyurl = curl_exec($ch);
if ($tinyurl!='Error' && $tinyurl!='') {
return $tinyurl;
} else {
trigger_error('arc_twitter failed to get a is.gd URL for '
.$url,E_USER_WARNING);
}
break;
case 'tinyurl': default: // create a shortened URL using TinyURL
$u = 'http://tinyurl.com/api-create.php?url='.urlencode($url);
curl_setopt($ch, CURLOPT_URL, $u);
$tinyurl = curl_exec($ch);
if ($tinyurl!='Error' && $tinyurl!='') {
return $tinyurl;
} else {
trigger_error('arc_twitter failed to get a TinyURL for '.$url,E_USER_WARNING);
}
}
return false; // fail
}
/*
*******************************************************************************
*/
class arc_twitter extends TwitterOAuth {
// Caching variables
private $_cache = true;
private $_cache_dir = './tmp';
private $_cache_time = 1800; // 30 minute cache
function __construct($consumer_key, $consumer_secret, $oauth_token = NULL
, $oauth_token_secret = NULL)
{
parent::__construct($consumer_key, $consumer_secret, $oauth_token
, $oauth_token_secret);
$this->format = 'xml';
$this->timeout = 15;
$this->connecttimeout = 15;
}
public function callbackURL($event,$step)
{
return hu.'textpattern/index.php?event='.$event.'&step='.$step;
}
// create Twitter and external links in text
public static function makeLinks($text)
{
$url = '/\b(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?([\/\w+\.]+)\b/i';
$text = preg_replace($url, "<a href='$0'>$0</a>", $text);
$url = '/\b(^|\s)www.([a-z_A-Z0-9]+)((\.[a-z]+)+)\b/i';
$text = preg_replace($url, "<a href='http://www.$2$3'>www.$2$3</a>", $text);
$text = preg_replace("/(^|\s)@([a-z_A-Z0-9]+)/",
"$1@<a href='http://twitter.com/$2'>$2</a>",$text);
$text = preg_replace("/(^|\s)(\#([a-z_A-Z0-9:_-]+))/",
"$1<a href='http://twitter.com/search?q=%23$3'>$2</a>",$text);
return $text;
}
public function get($url, $params = array())
{
$api_url = md5($url.urlencode(serialize($params)));
$data = '';
if ($this->_cache) { // check for cached xml
$data = $this->_retrieveCache($api_url);
}
if (empty($data)) {
$data = parent::get($url, $params);
if ($this->http_code===200 && $xml=simplexml_load_string($data)) { // save cache
$file = $this->_cache_dir.'/'.$api_url;
file_put_contents($file,$data,LOCK_EX);
return $xml;
} else { // failed to retrieve data from Twitter
if ($this->_cache) { // attempt to force cached xml return
$data = $this->_retrieveCache($api_url,true);
if ($data) return @simplexml_load_string($data);
}
return false;
}
} else { // return cached xml
return @simplexml_load_string($data);
}
} //end get()
function post($url, $params = array())
{
$data = parent::post($url,$params);
return simplexml_load_string($data);
}
function delete($url, $params = array())
{
$data = parent::delete($url,$params);
return simplexml_load_string($data);
}
// Cache methods
public function setCaching($cache=true)
{
$this->_cache = ($cache) ? true : false;
return true;
}
public function cacheDir($loc)
{
$this->_cache_dir = $loc;
return true;
}
public function cacheTime($mins)
{
$this->_cache_time = $mins*60; // convert minutes into seconds
return true;
}
private function _retrieveCache($url,$overide_timeout=false)
{
$file = $this->_cache_dir.'/'.$url;
if (file_exists($file)) {
$diff = time() - filemtime($file);
if ($overide_timeout || $diff < $this->_cache_time) {
return file_get_contents($file);
} else {
return false;
}
} else {
return false;
}
}
}
/*
* Abraham Williams (abraham@abrah.am) http://abrah.am
*
* The first PHP Library to support OAuth for Twitter's REST API.
*/
/**
* Twitter OAuth class
*/
class TwitterOAuth {
/* Contains the last HTTP status code returned. */
public $http_code;
/* Contains the last API call. */
public $url;
/* Set up the API root URL. */
public $host = "https://api.twitter.com/1/";
/* Set timeout default. */
public $timeout = 30;
/* Set connect timeout. */
public $connecttimeout = 30;
/* Verify SSL Cert. */
public $ssl_verifypeer = FALSE;
/* Respons format. */
public $format = 'json';
/* Decode returned json data. */
public $decode_json = TRUE;
/* Contains the last HTTP headers returned. */
public $http_info;
/* Set the useragnet. */
public $useragent = 'TwitterOAuth v0.2.0-beta2';
/* Immediately retry the API call if the response was not successful. */
//public $retry = TRUE;