forked from FerdiAgrio/PublishToTwitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PublishToTwitter.module
1020 lines (916 loc) · 42.9 KB
/
PublishToTwitter.module
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
namespace ProcessWire;
require 'TwitterOAuth/twitteroauth-autoloader.php';
use Abraham\TwitterOAuth\TwitterOAuth;
class PublishToTwitter extends WireData implements Module, ConfigurableModule {
/**
* first page status from where pages cannot be tweeted
*
* @return page status
*/
static protected $tweetFromStatus = Page::statusDraft;
const TwitterURL = "https://twitter.com/statuses/";
/**
* getModuleInfo is a module required by all modules to tell ProcessWire about them
*
* @return array
*
*/
public static function getModuleInfo() {
return array(
'title' => 'PublishToTwitter3',
'version' => '100',
'summary' => 'Offers an option to publish a page to Twitter when the date for publishing is past/scheduled.',
'href' => 'https://github.com/FerdiAgrio/PublishToTwitter/tree/master/',
'singular' => true,
'autoload' => 'template=admin|cron-publish-to-twitter',
'icon' => 'twitter',
'requires' => array('ProcessWire>=3.0.0'),
);
}
/**
* Set an array with fielddata for creation and checking before installation and uninstallation
*
* @return array
*
*/
static protected $modulefields = array(
0 => array(
'name' => 'publish_to_twitter',
'type' => 'FieldtypeCheckbox',
'label' => 'Publish to Twitter',
'showIf' => "publish_to_twitter_tid=0",
),
1 => array(
'name' => 'publish_to_twitter_tid',
'type' => 'FieldtypeText',
'initValue' => 0,
'label' => 'TweetID',
'description' => 'Automatically filled when Tweeted',
'collapsed' => Inputfield::collapsedBlank,
),
2 => array(
'name' => 'publish_to_twitter_delete',
'type' => 'FieldtypeCheckbox',
'label' => 'Delete tweet',
'collapsed' => Inputfield::collapsedNo,
'showIf' => "publish_to_twitter_tid!=0",
)
);
public function __construct() {
// populate defaults, which will get replaced with actual
// configured values before the init/ready methods are called
// $this->setArray(self::$defaults);
}
/**
* Module install action
*
*/
public function ___install() {
// Check that there are no required templates & fields already...
$this->checkInstall();
// create all module fields
foreach (self::$modulefields as $field_to_create) {
$field_creating = new Field();
$field_creating->type = $this->wire('modules')->get($field_to_create['type']);
$field_creating->name = $field_to_create['name'];
$field_creating->label = $field_to_create['label'];
$field_creating->collapsed = (isset($field_to_create['collapsed'])) ? $field_to_create['collapsed'] : Inputfield::collapsedNo;
if (isset($field_to_create['showIf'])) $field_creating->showIf = $field_to_create['showIf'];
if (isset($field_to_create['initValue'])) $field_creating->initValue = $field_to_create['initValue'];
if (isset($field_to_create['description'])) $field_creating->description = $field_to_create['description'];
$field_creating->tags = "PublishToTwitter";
$field_creating->icon = "twitter";
$field_creating->size = 0;
$field_creating->save();
}
}
/**
* Module uninstall action
*
*/
public function ___uninstall() {
$templates = $this->wire('templates');
$fields = $this->wire('fields');
$ptt = $this->wire('modules')->get('PublishToTwitter');
// remove all module fields from fieldgroups connected to templates
if ($ptt->publish_to_twitter_templates && count($ptt->publish_to_twitter_templates)) {
foreach($ptt->publish_to_twitter_templates as $ptt_template) {
// get fieldgroup from template and remove modulefields
$template = $templates->get($ptt_template);
$fg = $template->fieldgroup;
foreach (self::$modulefields as $field_to_remove) {
$f = $fields->get($field_to_remove['name']);
if ($fg->hasfield($f)) $fg->remove($f);
$fg->save();
}
}
}
// remove all module fields
foreach (self::$modulefields as $field_to_remove) {
$f = $fields->get($field_to_remove['name']);
if ($f && !$f->numFieldgroups()) $fields->delete($f);
elseif ($f) wire('session')->error("Could not remove field {$f->label}, please remove this field manually.");
}
}
public function ready() {
// well... ok
}
/**
* Returns true if module already installed
*
* @return bool
*/
private function checkInstall() {
if (count(self::$modulefields))
foreach(self::$modulefields as $checkfield)
if ($this->fields->get($checkfield['name']))
throw new WireException("There is already a field installed called '{$checkfield['name']}'");
return true;
}
/**
* Default configuration
* @return array fields
*/
public static function getDefaultConfig() {
return array(
// Preset for general settings
'publish_to_twitter_consumerkey' => '',
'publish_to_twitter_consumersecret' => '',
'publish_to_twitter_accesstoken' => '',
'publish_to_twitter_accesstokensecret' => '',
'publish_to_twitter_templates' => '',
'publish_to_twitter_datefield' => '',
'publish_to_twitter_titlefield' => '',
'publish_to_twitter_websitetitle' => '',
'publish_to_twitter_maxcharacters' => 115, // left for text (140 - 24 - 1) // max_num_char - link_num_char - space_char
'publish_to_twitter_maxcharlink' => 24, // left for text (140 - 24 - 1) // max_num_char - link_num_char - space_char
'publish_to_twitter_imagefield' => '',
'publish_to_twitter_imagefieldlimit' => 3,
'publish_to_twitter_imagefielddimlimit' => 1024, // 1024px images shouldn't exceed this size (used for either sides)
'publish_to_twitter_imagefieldsizelimit' => 3145728, // 3MB - images shouldn't exceed this size when tweeted
'publish_to_twitter_bitlylogin' => '',
'publish_to_twitter_bitlyaccesstoken' => '',
'publish_to_twitter_pre_prepend' => '',
'publish_to_twitter_pre_templates' => '',
'publish_to_twitter_pre_space' => '',
);
}
/**
* Initialize the module
*
*/
public function init() {
$this->addHookAfter('Pages::save', $this, 'checkPublishToTwitter');
$this->addHookBefore('ProcessPageEdit::execute', $this, 'getPublishToTwitterCSS');
}
/**
* Load CSS to hide the TweetID field
*
*/
public function getPublishToTwitterCSS(){
$config = $this->wire('config');
$config->styles->append($config->urls->siteModules . 'PublishToTwitter/PublishToTwitter.css');
}
/**
* Set required fields for use of this module
*
* @return InputfieldWrapper
*/
public static function getModuleConfigInputfields(array $data) {
$modules = wire('modules');
$templates = wire('templates');
$fields = wire('fields');
$fieldgroups = wire('fieldgroups');
$ar_modulefieldnames = array();
foreach (self::$modulefields as $field_to_connect)
$ar_modulefieldnames[] = $field_to_connect['name'];
foreach(self::getDefaultConfig() as $key => $value)
if(!isset($data[$key])) $data[$key] = $value;
// Get default Twitter settings
$_ck = $data['publish_to_twitter_consumerkey'];
$_cs = $data['publish_to_twitter_consumersecret'];
$_at = $data['publish_to_twitter_accesstoken'];
$_as = $data['publish_to_twitter_accesstokensecret'];
$_tp = $data['publish_to_twitter_templates'];
$_df = $data['publish_to_twitter_datefield'];
$_tf = $data['publish_to_twitter_titlefield'];
$_wt = $data['publish_to_twitter_websitetitle'];
$_mc = $data['publish_to_twitter_maxcharacters'];
$_ml = $data['publish_to_twitter_maxcharlink'];
$_if = $data['publish_to_twitter_imagefield'];
$_il = $data['publish_to_twitter_imagefieldlimit'];
$_id = $data['publish_to_twitter_imagefielddimlimit'];
$_is = $data['publish_to_twitter_imagefieldsizelimit'];
$_bl = $data['publish_to_twitter_bitlylogin'];
$_ba = $data['publish_to_twitter_bitlyaccesstoken'];
$_pp = $data['publish_to_twitter_pre_prepend'];
$_pt = $data['publish_to_twitter_pre_templates'];
$_ps = $data['publish_to_twitter_pre_space'];
// update/check data only after post
$wp = wire()->input->post;
if (wire('page')->template == 'admin' && count($wp) && !$wp->uninstall) {
$_ck = $wp->publish_to_twitter_consumerkey;
$_cs = $wp->publish_to_twitter_consumersecret;
$_at = $wp->publish_to_twitter_accesstoken;
$_as = $wp->publish_to_twitter_accesstokensecret;
$_tp = $wp->publish_to_twitter_templates;
$_df = $wp->publish_to_twitter_datefield;
$_tf = $wp->publish_to_twitter_titlefield;
$_wt = $wp->publish_to_twitter_websitetitle;
$_mc = $wp->publish_to_twitter_maxcharacters;
$_ml = $wp->publish_to_twitter_maxcharlink;
$_if = $wp->publish_to_twitter_imagefield;
$_il = $wp->publish_to_twitter_imagefieldlimit;
$_id = $wp->publish_to_twitter_imagefielddimlimit;
$_is = $wp->publish_to_twitter_imagefieldsizelimit;
$_bl = $wp->publish_to_twitter_bitlylogin;
$_ba = $wp->publish_to_twitter_bitlyaccesstoken;
$_pp = $wp->publish_to_twitter_pre_prepend;
$_pt = $wp->publish_to_twitter_pre_templates;
$_ps = $wp->publish_to_twitter_pre_space;
if(!empty($_ck) && !empty($_cs) && !empty($_at) && !empty($_as)) {
// now we try to connect to Twitter with an OAuth connection
$query = array();
$result = $modules->get('PublishToTwitter')->TwitterConnection('verify', $_ck, $_cs, $_at, $_as, $query);
if ($result) {
// check for errors
if(isset($result->errors) && count($result->errors)) {
foreach($result->errors as $error)
wire('pages')->error("Twitter response: $error->message (Error code: $error->code)");
} elseif (isset($result->name)) {
// successful connected, show accountname
wire('session')->message("Connection to Twitter was successful (accountname: <a href='https://twitter.com/{$result->name}' target='_blank'>{$result->name}</a> <i class='fa fa-external-link'></i> was found)", Notice::allowMarkup);
} else {
// successful connected
wire('session')->message("Connection to Twitter was successful");
}
}
}
// when the templatefield is filled, get all fieldgroups to skip them at removing
$skip_fgs = array();
if ($_tp && count($_tp)) {
foreach($_tp as $ptt_template) {
// get fieldgroup from template and add modulefields
$template = $templates->get($ptt_template);
$fg = $template->fieldgroup;
$skip_fgs[] = $fg->name;
}
}
foreach ($ar_modulefieldnames as $field_to_connect) {
$f = $fields->get($field_to_connect);
$fgs = $f->getFieldgroups();
if (count($fgs))
foreach ($fgs as $fg)
if (!in_array($fg->name, $skip_fgs)) {
wire('session')->message("Fieldgroup: '{$f->name}' removed");
$fg->remove($f);
$fg->save();
}
}
// when a template is selected, add the publish_to_twitter field to it
if ($_tp && count($_tp)) {
foreach($_tp as $ptt_template) {
// get fieldgroup from template and add modulefields
$template = $templates->get($ptt_template);
$fg = $template->fieldgroup;
foreach ($ar_modulefieldnames as $field_to_connect) {
wire('session')->message("Field: '{$field_to_connect}' attached to fieldgroup '{$fg->name}'");
$fg->add($fields->get($field_to_connect));
}
$fg->save();
}
}
}
// set and return all fields for this module
$inputfields = new InputfieldWrapper();
// Twitter settings:
// Twitter Consumer Key
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_consumerkey');
$f->label = __('Twitter Consumer Key');
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_ck);
$f->placeholder = __('Get OAuth keys and tokens at https://apps.twitter.com/');
$f->notes = __('Note: will be verified when submitting module data.');
$f->collapsed = Inputfield::collapsedPopulated;
$inputfields->add($f);
// Twitter Consumer Secret
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_consumersecret');
$f->label = __('Twitter Consumer Secret');
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_cs);
$f->placeholder = __('Get OAuth keys and tokens at https://apps.twitter.com/');
$f->notes = __('Note: will be verified when submitting module data.');
$f->collapsed = Inputfield::collapsedPopulated;
$inputfields->add($f);
// Twitter Access Token
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_accesstoken');
$f->label = __('Twitter Access Token');
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_at);
$f->placeholder = __('Get OAuth keys and tokens at https://apps.twitter.com/');
$f->notes = __('Note: will be verified when submitting module data.');
$f->collapsed = Inputfield::collapsedPopulated;
$inputfields->add($f);
// Twitter Access Token Secret
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_accesstokensecret');
$f->label = __('Twitter Access Token Secret');
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_as);
$f->placeholder = __('Get OAuth keys and tokens at https://apps.twitter.com/');
$f->notes = __('Note: will be verified when submitting module data.');
$f->collapsed = Inputfield::collapsedPopulated;
$inputfields->add($f);
// Other settings fields
// template(s) field to check for checkbox
$f = $modules->get('InputfieldAsmSelect');
$f->attr('name', 'publish_to_twitter_templates');
$f->label = __('Publish to Twitter templates');
$f->description = __('Pages using these templates can be tweeted.');
$f->notes = __('Warning: removing a template will also remove Twitterdata from pages which use this template.');
foreach ($templates->find("flags!=" . Template::flagSystem . ",sort=name") as $template) {
$f->addOption($template->id, $template->name);
}
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_tp);
$inputfields->add($f);
// date field to check with current date
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'publish_to_twitter_datefield');
$f->label = __('Datefield to check for publication');
$f->description = __('This field will be checked for immediate/future tweeting.');
foreach ($fields->find('sort=label,type=FieldtypeDatetime|FieldtypeText') as $field) {
if (!in_array($field->name, $ar_modulefieldnames)) $f->addOption($field->name, $field->label);
}
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_df);
$inputfields->add($f);
// page title field
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'publish_to_twitter_titlefield');
$f->label = __('Page title field');
$f->description = __('This field will be placed in front of the Tweet.');
$f->notes = __('Note: shortened when too long.');
foreach ($fields->find('sort=label,type=FieldtypePageTitle|FieldtypeText') as $field) {
if (!in_array($field->name, $ar_modulefieldnames)) $f->addOption($field->name, $field->label);
}
$f->required = true;
$f->columnWidth = 50;
$f->attr('value', $_tf);
$inputfields->add($f);
// website title
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_websitetitle');
$f->label = __('Title of website');
$f->description = __('Will be placed after the page title.');
$f->notes = __('Note: only when enough space available.');
$f->columnWidth = 50;
$f->attr('value', $_wt);
$inputfields->add($f);
// page image field
$f = $modules->get('InputfieldSelect');
$f->attr('name', 'publish_to_twitter_imagefield');
$f->label = __('Page image(s) field');
$f->description = __('Image to attach to the Tweet.');
$f->notes = __('Note: When multiple, the max. number will be attached.');
foreach ($fields->find('sort=label,type=FieldtypeImage|FieldtypeCropImage|FieldtypeCroppableImage3') as $field) {
$f->addOption($field->name, $field->label);
}
$f->columnWidth = 50;
$f->attr('value', $_if);
$inputfields->add($f);
// max number of images to tweet
$f = $modules->get('InputfieldInteger');
$f->attr('name', 'publish_to_twitter_imagefieldlimit');
$f->label = __('Number of images');
$f->description = __('Max. number of images to attach.');
$f->notes = __('Note: please mind the time to upload, max. 4');
$f->columnWidth = 50;
$f->attr('min', 1);
$f->attr('max', 4);
$f->attr('value', $_il);
$inputfields->add($f);
// template(s) field to check for checkbox
$f = $modules->get('InputfieldAsmSelect');
$f->attr('name', 'publish_to_twitter_pre_templates');
$f->label = __('Use prepend text for templates');
foreach ($templates->find("flags!=" . Template::flagSystem . ",sort=name") as $template) {
$f->addOption($template->id, $template->name);
}
$f->notes = __('Tweeting pages using these templates will be altered.');
$f->columnWidth = 34;
$f->attr('value', $_pt);
$inputfields->add($f);
// Prepend text
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_pre_prepend');
$f->label = __('Prepend text');
$f->columnWidth = 33;
$f->attr('value', $_pp);
$f->stripTags = true;
$f->placeholder = __('Lorem ipsum -');
$f->notes = __('This text will be placed in front of the Tweet.');
$inputfields->add($f);
// Add space after text?
$f = $modules->get('InputfieldCheckbox');
$f->attr('name', 'publish_to_twitter_pre_space');
$f->label = __('Add a space after the prepend text');
$f->columnWidth = 33;
$f->checked = $_ps;
$f->notes = __('Spaces are automatically stripped from the text. Activating this option will append one space.');
$inputfields->add($f);
// Bit.ly login
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_bitlylogin');
$f->label = __('Bit.ly Login');
$f->description = __('');
$f->notes = __('');
$f->columnWidth = 50;
$f->attr('value', $_bl);
$inputfields->add($f);
// Bit.ly access token
$f = $modules->get('InputfieldText');
$f->attr('name', 'publish_to_twitter_bitlyaccesstoken');
$f->label = __('Bit.ly Access Token');
$f->description = __('');
$f->notes = __('');
$f->columnWidth = 50;
$f->attr('value', $_ba);
$inputfields->add($f);
// all hidden fields:
// number of characters available for text
$f = $modules->get('InputfieldHidden');
$f->attr('name', 'publish_to_twitter_maxcharacters');
$f->attr('value', $_mc);
$inputfields->add($f);
// number of characters per link in text
$f = $modules->get('InputfieldHidden');
$f->attr('name', 'publish_to_twitter_maxcharlink');
$f->attr('value', $_ml);
$inputfields->add($f);
// max dimension (longest size)
$f = $modules->get('InputfieldHidden');
$f->attr('name', 'publish_to_twitter_imagefielddimlimit');
$f->attr('value', $_id);
$inputfields->add($f);
// maximum filesize of image
$f = $modules->get('InputfieldHidden');
$f->attr('name', 'publish_to_twitter_imagefieldsizelimit');
$f->attr('value', $_is);
$inputfields->add($f);
return $inputfields;
}
/**
* Before Pages::save check if this page should be Tweeted
* @return void
*/
public function checkPublishToTwitter($event) {
$page = $event->arguments('page');
// don't try anything when not all required fields are set
$valid = $this->checkRequiredFields();
if ($valid) return $this->error($valid);
// check all module required variables
$ptt = $this->modules->get('PublishToTwitter');
if (!in_array($page->template->id, $ptt->publish_to_twitter_templates)) return;
// preset error and message arrays
$ptt_err_array = $ptt_msg_array = array();
// place module variables into easy to use ones
$_ck = $ptt->publish_to_twitter_consumerkey;
$_cs = $ptt->publish_to_twitter_consumersecret;
$_at = $ptt->publish_to_twitter_accesstoken;
$_as = $ptt->publish_to_twitter_accesstokensecret;
$_df = $ptt->publish_to_twitter_datefield;
$_tf = $ptt->publish_to_twitter_titlefield;
$_wt = $ptt->publish_to_twitter_websitetitle;
$_mc = $ptt->publish_to_twitter_maxcharacters;
$_ml = $ptt->publish_to_twitter_maxcharlink;
$_if = $ptt->publish_to_twitter_imagefield;
$_il = $ptt->publish_to_twitter_imagefieldlimit;
$_pp = $ptt->publish_to_twitter_pre_prepend;
$_pt = $ptt->publish_to_twitter_pre_templates;
$_ps = $ptt->publish_to_twitter_pre_space;
// check for filled in fields and post is done
if (wire()->input->post->id && $page->publish_to_twitter && !$page->publish_to_twitter_tid) {
// page is saved (preventing loop), and checkbox for Twitter publishing is set, but page has not been Tweeted before (no TweetID)
if ($page->status >= self::$tweetFromStatus && !$page->parents('/trash/')) {
// page status is not 'Published'
if ($page->get($_df) && time() > $page->get($_df)) {
// publicationdate is in the past
$this->message("This page will ONLY be tweeted when status is set 'Published'.");
return;
} else {
// publicationdate is in the future
$this->message("This page will NOT be tweeted until the status is set 'Published'.");
return;
}
} elseif ($page->get($_df) && time() > $page->get($_df)) {
// publicationdate is in the past, tweet now
$ptt_msg_array[] = "Trying to tweet this page now...";
} else {
// publicationdate is in the future, tweet when cron will find it
$this->message("This page will be tweeted when the publicationdate is reached.");
return;
}
// try to tweet
$result = self::createTweet($page);
if ($result) {
// check for errors
if(isset($result->errors) && count($result->errors)) {
foreach($result->errors as $error) {
$ptt_err_array[] = "Twitter response: {$error->message} (Error code: {$error->code})";
}
} else {
$ptt_msg_array[] = sprintf("Tweeted page - <a target='_blank' href='%s{$result->id}'>#{$result->id}</a> <i class='fa fa-external-link'></i>.", self::TwitterURL);
}
}
} elseif (wire()->input->post->id && wire()->input->post->publish_to_twitter && wire()->input->post->publish_to_twitter_tid) {
// this page is already tweeted
$ptt_err_array[] = sprintf("This page is already tweeted; see <a target='_blank' href='%s{$page->publish_to_twitter_tid}'>Tweet</a> <i class='fa fa-external-link'></i>.", self::TwitterURL);
// unset checkbox so this item wont be tweeted by cron
$page->publish_to_twitter = 0;
$page->save();
} elseif (wire()->input->post->id && $page->publish_to_twitter_tid && wire()->input->post->publish_to_twitter_delete) {
// try to delete a tweet by ID
$query = array(
"id" => $page->publish_to_twitter_tid,
);
$result = $ptt->TwitterConnection('delete', $_ck, $_cs, $_at, $_as, $query);
if ($result) {
// check for errors
if(isset($result->errors) && count($result->errors)) {
foreach($result->errors as $error) {
$ptt_err_array[] = "Twitter response: {$error->message} (Error code: {$error->code})";
if ($error->code == 144) {
// false tweetID, remove option to delete and tweetID
$page->publish_to_twitter_tid = "";
// unset checkbox so this item can be tweeted again
$page->publish_to_twitter_delete = 0;
$page->save();
$ptt_err_array[] = "Unable to determine correct TweetID, removed user-input";
}
}
} else {
// remove TweetID from page
$page->publish_to_twitter_tid = "";
// unset checkbox so this item can be tweeted again
$page->publish_to_twitter_delete = 0;
$page->save();
$ptt_msg_array[] = "Successful removed this tweet.";
}
}
}
// show errors
foreach ($ptt_err_array as $ptt_err)
$this->error($ptt_err, Notice::allowMarkup);
// show messages
foreach ($ptt_msg_array as $ptt_msg)
$this->message($ptt_msg, Notice::allowMarkup);
return;
}
/**
* Checks for pages that need to be tweeted, tweets them and saves log in {logpath}/PublishToTwitterCron.txt
*
* return void
*/
public function RunCronPublishToTwitter() {
$ptt_log_entries = array();
$ptt_log_entries[] = "Cron started";
// don't try anything when not all required fields are set
$valid = $this->checkRequiredFields();
if ($valid) return $this->error($valid);
// preset error and message array
$ptt_msg_array = $ptt_err_array = array();
// check all module required variables
if (!count($ptt_err_array)) {
$ptt = $this->modules->get('PublishToTwitter');
// place module variables into easy to use ones
$_tf = $ptt->publish_to_twitter_titlefield;
$_df = $ptt->publish_to_twitter_datefield;
//set default in case no datefield is selected
$page_df = strtotime('+10 minutes');
if ($_df)
$page_df = wire('fields')->get($_df)->name;
$page_tf = $_tf;
// Select published pages with publish_to_twitter set to true and where publicationdate is past current time
$tweet_pages = wire("pages")->find(
"publish_to_twitter=1,".
"publish_to_twitter_tid='',".
"{$page_df}<=now,".
"status<" . self::$tweetFromStatus . ",".
"has_parent!=/trash/,".
"template=". implode("|", $ptt->publish_to_twitter_templates)
);
if (count($tweet_pages)) {
$ptt_msg_array[] = __(count($tweet_pages) . ' page(s) found');
foreach($tweet_pages as $tp) {
// try to tweet
$result = self::createTweet($tp);
if ($result) {
// check for errors
if(isset($result->errors) && count($result->errors)) {
foreach($result->errors as $error) {
$ptt_err_array[] = __("Twitter response: {$error->message} (Error code: {$error->code})");
}
} else {
$ptt_msg_array[] = __(sprintf("Tweeted this page - {$tp->httpUrl} to %s{$result->id}", self::TwitterURL));
}
}
}
} else {
$ptt_msg_array[] = __('No pages found.');
}
} else {
// not all required module fields are set
$ptt_err_array[] = __("This action cannot be executed, please fill in all required fields in the Publish To Twitter module page.");
}
// show errors
foreach ($ptt_err_array as $ptt_err) {
$ptt_log_entries[] = "Error: " . $ptt_err;
}
// show messages
foreach ($ptt_msg_array as $ptt_msg) {
$ptt_log_entries[] = $ptt_msg;
}
wire('log')->save("publishtotwitter", implode(" - ", $ptt_log_entries));
return;
}
/**
* Check required fields before executing function by module inputdata
*
* @return string|bool (errormessage or false)
*/
public function checkRequiredFields() {
$ptt = $this->wire('modules')->get('PublishToTwitter');
foreach ($ptt->data as $req_field => $val) {
switch ($req_field) {
case "publish_to_twitter_consumerkey":
case "publish_to_twitter_consumersecret":
case "publish_to_twitter_accesstoken":
case "publish_to_twitter_accesstokensecret":
case "publish_to_twitter_datefield":
case "publish_to_twitter_titlefield":
// text
if (empty($val)) return __("Not all required module fields are set, please validate.");
case "publish_to_twitter_templates":
// array
if (!count($val)) return __("Not all required module fields are set, please validate.");
}
}
return false;
}
/*
* Build and place a complete Tweet with page and module data
*
* @param object page
* @return object Twitter response
*/
public function createTweet($p) {
$ptt = $this->modules->get('PublishToTwitter');
$_ck = $ptt->publish_to_twitter_consumerkey;
$_cs = $ptt->publish_to_twitter_consumersecret;
$_at = $ptt->publish_to_twitter_accesstoken;
$_as = $ptt->publish_to_twitter_accesstokensecret;
$_tf = $ptt->publish_to_twitter_titlefield;
$_wt = $ptt->publish_to_twitter_websitetitle;
$_mc = $ptt->publish_to_twitter_maxcharacters;
$_ml = $ptt->publish_to_twitter_maxcharlink;
$_if = $ptt->publish_to_twitter_imagefield;
$_il = $ptt->publish_to_twitter_imagefieldlimit;
$_id = $ptt->publish_to_twitter_imagefielddimlimit;
$_is = $ptt->publish_to_twitter_imagefieldsizelimit;
$_pp = $ptt->publish_to_twitter_pre_prepend;
$_pt = $ptt->publish_to_twitter_pre_templates;
$_ps = $ptt->publish_to_twitter_pre_space;
if ($p->template == 'hearing')
{
$days = array("So", "Mo", "Di", "Mi", "Do", "Fr", "Sa");
$text = "Verhandlung i.S. " . $this->wordLimiter($p->matter, 45) . ": " . $this->wordLimiter($p->location, 20) . ", " . $days[date("w")] . " " . date("d.m.Y H:i", $p->date_time) . " " . $this->shortenBitLy("https://piraten-bsg.de/verhandlungen/") . " /" . $p->modifiedUser->tweet_acronym;
$query = array(
"status" => array(
"text" => $text,
"id" => $p->id,
)
);
$result = $ptt->TwitterConnection("spost", $_ck, $_cs, $_at, $_as, $query);
}
else if ($p->template == 'case')
{
if (strlen($p->docurl) > 0)
{
$text = $this->wordLimiter($p->tweet, 110) . " " . $this->shortenBitLy($p->docurl) . " /" . $p->modifiedUser->tweet_acronym;
}
else
{
$text = $this->wordLimiter($p->tweet, 135) . " /" . $p->modifiedUser->tweet_acronym;
}
$query = array(
"status" => array(
"text" => $text,
"id" => $p->id,
)
);
$result = $ptt->TwitterConnection("spost", $_ck, $_cs, $_at, $_as, $query);
}
else if ($p->template == 'news_item')
{
$text = $this->wordLimiter($p->getUnformatted('body'), 110) . " " . $this->shortenBitLy('https://piraten-bsg.de/') . " /" . $p->modifiedUser->tweet_acronym;
$query = array(
"status" => array(
"text" => $text,
"id" => $p->id,
)
);
$result = $ptt->TwitterConnection("spost", $_ck, $_cs, $_at, $_as, $query);
}
else
{
$query = array(
"status" => array(
"text" => $p->getUnformatted($_tf),
"id" => $p->id,
"mc" => $_mc,
"ml" => $_ml,
"wt" => ((strlen($_wt)) ? " {$_wt}" : ""),
"pp" => "",
)
);
// check if template (of page to tweet) is set to alter tweettext
if (($_pt && count($_pt)) && in_array($p->template->id, $_pt)) {
$query["status"]["pp"] = $_pp . ($_ps ? " " : "");
}
// when there is media, append it to the twitter query
if ($_if && wire('fields')->get($_if) && $p->get($_if) && count($p->get($_if))) {
// imagefield found and filled
$media = "";
$_ic = 0;
foreach ($p->get($_if) as $image) {
// default image properties
$im_opts = array("upscaling" => false);
// resize the twitterimage, we don't want to spoil datatraffic
$_ti = ($image->width > $image->height) ? $image->size($_id, 0, $im_opts) : $image->size(0, $_id, $im_opts);
// images for Twitter should not exceed 3MB
if ($_ti->filesize > $_is) break;
// upload media to twitter and get an ID for in tweet
$media = (empty($media)) ? $_ti->filename : implode(",", array($media, $_ti->filename));
$_ic++;
if ($_ic >= $_il) break;
}
// append media to status as imploded string with separator "," (comma)
$query["media_ids"] = $media;
}
// try to tweet
$result = $ptt->TwitterConnection("post", $_ck, $_cs, $_at, $_as, $query);
}
// when all ok, update page
if ($result && (!isset($result->errors) || !count($result->errors))) {
// set outputformatting for correct saving
$p->setOutputFormatting(false);
// save TweetID to page
$p->publish_to_twitter_tid = $result->id;
// unset checkbox so this item wont be tweeted by cron
$p->publish_to_twitter = 0;
$p->save();
}
// return complete result for response to user/cron
return $result;
}
/**
* Load Twitter OAuth and call function
* @param $_f string method to use when talking to Twitter
* @param $_ck string Twitter credential
* @param $_cs string Twitter credential
* @param $_at string Twitter credential
* @param $_as string Twitter credential
* @param $query array Tweet data
*
* @return object|false Twitter response|false when non-supported method is used
*/
public function ___TwitterConnection($f, $_ck, $_cs, $_at, $_as, $query) {
switch ($f) {
case 'verify' :
$toa = new TwitterOAuth($_ck, $_cs, $_at, $_as);
return $toa->get('account/verify_credentials', $query);
case 'spost' :
$text = $query["status"]["text"];
$post_query = array("status" => $text);
$toa = new TwitterOAuth($_ck, $_cs, $_at, $_as);
return $toa->post('statuses/update', $post_query);
case 'post' :
// split array $query to look for media
$media = (!empty($query["media_ids"])) ? explode(",", $query["media_ids"]) : array();
$media_no = count($media);
// combine all texts and strip the number of characters which can be used (if needed)
$text = $query["status"]["text"] . $query["status"]["wt"];
// when a prepend text is set, prepend it
if (!empty($query["status"]["pp"])) {
$text = $query["status"]["pp"] . $text;
}
if (strlen($text) > $query["status"]["mc"])
// text with website title is exceeding limit (including optional media links) so limit text to only page title
// Twitter reserves for all media only one time the number of characters for media (so no multiplication needed)
// since 09-2016 the media doesn't count anymore
$text = $this->wordLimiter($query["status"]["text"], $query["status"]["mc"]);
// add link of page (calculated in max_characters==mc)
$text .= " " . $this->shortenBitLy(wire('pages')->get($query["status"]["id"])->httpUrl);
$post_query = array("status" => $text);
// add media link(s) when available
$media_str = "";
foreach ($media as $mediafile) {
$response = $this->___TwitterConnection("upload", $_ck, $_cs, $_at, $_as, ["media" => $mediafile]);
if(isset($response->media_id_string)) {
$media_str = (empty($post_query["media_ids"])) ? $response->media_id_string : implode(",", array($post_query["media_ids"], $response->media_id_string));
}
$post_query["media_ids"] = $media_str;
}
$toa = new TwitterOAuth($_ck, $_cs, $_at, $_as);
return $toa->post('statuses/update', $post_query);
case 'delete' :
$toa = new TwitterOAuth($_ck, $_cs, $_at, $_as);
return $toa->post('statuses/destroy', $query);
case 'upload' :
$toa = new TwitterOAuth($_ck, $_cs, $_at, $_as);
return $toa->upload('media/upload', $query, true);
}
return false;
}
/**
* Get bit.ly shortened link or when error return given url
*
* @param $url string URL to shorten
* @return string shortened URL
*/
public function shortenBitLy($url) {
$ptt = $this->modules->get('PublishToTwitter');
$_bl = $ptt->publish_to_twitter_bitlylogin;
$_ba = $ptt->publish_to_twitter_bitlyaccesstoken;
// return url
return (!empty($url) && !empty($_bl) && !empty($_ba)) ? $this->___BitLyConnection($url, $_bl, $_ba) : $url;
}
/**
* Make a CURL connection to the bit.ly API and try to get a shortened link or when error return given url
*
* @param $url string URL to shorten
* @param $login string bit.ly login name
* @param $accesstoken string bit.ly accesstoken
* @param $apiurl string url of bit.ly api
* @param $format string xml or json
* @param $version string api version
* @return string shortened URL
*/
public function ___BitLyConnection($url, $login, $accesstoken, $apiurl = 'https://api-ssl.bitly.com/', $format='xml', $version='3') {
//create the URL
$bitly = $apiurl;
$bitly .= 'v'.$version.'/shorten';
$bitly .= '?longUrl='.urlencode($url);
$bitly .= '&login='.$login;
$bitly .= '&access_token='.$accesstoken;
$bitly .= '&format='.$format;
//get the url
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $bitly);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
//parse depending on desired format
if(strtolower($format) == 'json') {
$json = @json_decode($response,true);
return (is_array($json) && isset($json['status_code']) && $json['status_code'] == '200' && isset($json['data']) && isset($json['data']['url'])) ? $json['data']['url'] : $url;
} else {
$xml = simplexml_load_string($response);
return (is_object($xml) && isset($xml->status_code) && $xml->status_code == '200' && isset($xml->data) && isset($xml->data->url)) ? $xml->data->url : $url;
}
}
/**
* Text alteration when given string is exceeding limit, appends suffix
*
* @param $str string Text to check
* @param $limit int number of characters
* @param $endstr string suffix after limited text if needed
* @return string formatted string
*/