-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessSendNewsletter.module
executable file
·1077 lines (936 loc) · 34.5 KB
/
ProcessSendNewsletter.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
/**
* Send newsletter to subscribed users using various beckends
* by Piotr Markiewicz
*
* ProcessWire 2.x
* Copyright (C) 2014 by Ryan Cramer
* Licensed under GNU/GPL v2, see LICENSE.TXT
*
* http://processwire.com
*
*/
class ProcessSendNewsletter extends Process implements ConfigurableModule {
const minVersion = '2.8.8';
public static function getModuleInfo() {
return array(
'title' => 'Send Newsletter',
'summary' => 'Send newsletter to subscribed users.',
'version' => 020,
'icon' => 'paper-plane',
'page' => array(
'name' => 'send-newsletter',
'parent' => 'setup',
),
'requires' => 'ProcessWire>=2.8.8',
'installs' => 'Subscribers',
'autoload' => false
);
}
//initial settings
protected static $defaults = array(
'header' => 'Hi {{NAME}}, this is a new issue of our newsletter.',
'footer' => 'You have received this newsletter because you subscribed on our website.',
'unsubscribeText' => 'Click here to unsubscribe.',
'unsubscribeUrl' => 'subscribers_url',
'senderRole' => 'superuser',
'receiverRole' => 'newsletter',
'backend' => '',
'useNames' => '',
'fromEmail' => 'newsletter@yourdomain.com',
'fromName' => 'My website newsletter',
'backendPass' => '',
'hideActionText' => false,
'hideActionLink' => false,
);
//names of fields used during install
protected $templateName = 'SendNewsletter';
protected $fieldBody = 'Newsletter_history_body';
protected $fieldDetails = 'Newsletter_history_details';
protected $fieldActionButton = "Newsletter_history_action";
//values of fields used for creating newsletter
protected $title = "";
protected $body = "";
protected $actionText = "";
protected $actionLink ="";
protected $template ="";
protected $newsletterGroup = "";
protected $pageName = "";
protected $log = 'newsletter';
protected static $status = array(
'SENT' => 'SENT',
'SAVED' => 'SAVED',
'ERROR' => 'ERROR'
);
/**
* Initialize the newsletter module
*/
public function init() {
if(!$this->user->hasRole($this->config('senderRole')) ) throw new WirePermissionException("This module requires special access");
$this->modules->get('JqueryWireTabs');
$this->modules->get('JqueryMagnific');
$this->config->scripts->add($this->config->urls->ProcessSendNewsletter . 'ProcessSendNewsletter.js');
$this->config->scripts->add($this->config->urls->ProcessSendNewsletter . 'wysiwyg/trumbowyg.js');
$url = $this->config->url('page');
$this->config->js('iconPath', $url);
parent::init();
}
/**
* Ensure that everything is where we need it to be
*
* Returns false if not.
*
*/
protected function setup() {
if (!$this->user->hasRole($this->config('senderRole')) || !$this->user->hasPermission('newsletter-sender')) {
$this->error("Sorry, but you can't send newsletters. Ask administrator for a permission");
return false;
}
return true;
}
/**
* Build the initial form used for sending newsletters
*
*/
protected function buildForm() {
$templateFileName = "";
//info about opened page
$form = $this->modules->get('InputfieldForm');
$form->attr('id', 'NewsletterModule');
$form->attr('action', $this->wire('page')->url );
if ($this->pageName) {
$title = $this->pages->get("name=".$this->pageName)->title;
$prepended = "<div id='NewsletterNotes' class='Inputfields'><div class='InputfieldHeader'>" .
"<p class='notes'><em>You are editing </em>" .($title ? $title : "<i>Untitled</i>")."</p>" .
"</div></div>";
$form->attr('prependMarkup', $prepended);
}
// First Tab - Main
$tab = new InputfieldWrapper();
$tab->attr('title', $this->_('Create'));
$id = 'NewsletterMain';
$tab->attr('id', $id);
$tab->class .= ' WireTab';
$f = $this->modules->get('InputfieldText');
$f->attr('name', 'newsletter_title');
$f->attr('value', $this->title);
$f->label = $this->_('Email subject');
$f->columnWidth = 50;
$f->required = true;
$tab->add($f);
$f = $this->modules->get('InputfieldTextarea');
$f->attr('name', 'newsletter_body');
$f->attr('value', $this->body);
$f->label = $this->_('Email text');
$f->description = 'Text added as header: <<' .$this->data['header'] . '>> Text added as footer: <<' .$this->data['footer'] .'>>' ;
$f->attr('rows', 5);
$f->required = true;
$tab->add($f);
if (!$this->config('hideActionText')) {
$f = $this->modules->get('InputfieldText');
$f->attr('name', 'newsletter_button_text');
$f->attr('value', $this->actionText);
$f->label = $this->_('Button text');
$f->columnWidth = 50;
$tab->add($f);
}
if (!$this->config('hideActionLink')) {
$f = $this->modules->get('InputfieldURL');
$f->attr('name', 'newsletter_button_link');
$f->attr('value', $this->actionLink);
$f->label = $this->_('Button link');
$f->columnWidth = 50;
$tab->add($f);
}
$f = $this->modules->get('InputfieldSelect');
$f->attr('name', 'newsletter_group');
$f->label = $this->_('Newsletter group - send to:');
$f->columnWidth = 30;
$f->collapsed = Inputfield::collapsedYes;
foreach ($this->config('receiverRole') as $role) {
$arr = ($this->newsletterGroup == $role ? array("selected" => 1) : array());
$count = $this->wire('users')->count("roles=" . $role);
$f->addOption($role, "$role - $count", $arr);
}
//add all if there is more groups
if (count($this->config('receiverRole')) > 1) {
$arr = ($this->newsletterGroup == 'all' ? array("selected" => 1) : array());
$count = $this->wire('users')->count("roles=" . implode("|", $this->config('receiverRole')));
$f->addOption('all', "all - $count", $arr);
}
$f->required = true;
$tab->add($f);
$f = $this->modules->get('InputfieldSelect');
$f->attr('name', 'newsletter_template');
$f->attr('value', $this->title);
$f->label = $this->_('Template');
$f->columnWidth = 30;
$f->required = true;
$f->collapsed = Inputfield::collapsedYes;
//find available templates
$files = scandir(dirname ( __FILE__ ) . "/templates");
foreach ($files as $file) {
//get file names and append selected where it should be
if (strpos($file, ".html") == true) {
$name = str_replace(".html", "", $file);
$template = str_replace(".html", "", $this->template);
$arr = ($template == $name ? array("selected" => 1) : array());
$f->addOption($file, $name, $arr);
if ($templateFileName === "" || isset($arr['selected'])) {
$templateFileName = $file;
}
}
}
$tab->add($f);
$f = $this->modules->get('InputfieldMarkup');
$f->attr('name', 'template_preview');
$f->value = "<img src='{$this->getTemplateImage($templateFileName)}' alt='Unable to find template preview'/>";
$f->label = $this->_('Template preview');
$f->columnWidth = 40;
$f->collapsed = Inputfield::collapsedYes;
$tab->add($f);
$f = $this->modules->get('InputfieldHidden');
$f->attr('name', 'newsletter_page_name');
$f->attr('value', $this->pageName);
$form->add($f);
$f = $this->modules->get('InputfieldSubmit');
$f->attr('name', 'submit_send');
$f->attr('title', $this->_('Send this newsletter to subscribers'));
$f->attr('value', $this->_('Send'));
$f->attr('onclick', "return confirm('" . $this->_('Send newsletter now?') . "')");
$f->icon = 'paper-plane';
$tab->add($f);
$f = $this->modules->get('InputfieldSubmit');
$f->attr('name', 'submit_test');
$f->attr('value', $this->_('Test'));
$f->attr('title', $this->_('Send this newslleter to yourself only'));
$f->attr('onclick', "return confirm('" . $this->_('Send test newsletter to '.$this->user->email.'?') . "')");
$f->icon = 'cogs';
$tab->add($f);
$f = $this->modules->get('InputfieldSubmit');
$f->attr('name', 'submit_save');
$f->attr('value', $this->_('Save'));
$f->attr('title', $this->_('You can save a newsletter and go back to it later from "History" tab.'));
$f->icon = 'save';
$tab->add($f);
$f = $this->modules->get('InputfieldButton');
$f->attr('name', 'submit_preview');
$f->attr('id', 'button_preview');
$f->attr('value', $this->_('Preview'));
$f->attr('title', $this->_('Open a dialog box with a newsletter preview.'));
$f->icon = 'binoculars';
$f->href = $this->wire('page')->url . 'Preview/?preview=1&modal=1';
$tab->add($f);
$form->add($tab);
//second tab - history
$tab = new InputfieldWrapper();
$tab->attr('title', $this->_('History'));
$id = $this->className() . 'History';
$tab->attr('id', $id);
$tab->class .= ' WireTab';
//table with newsletter history
$table = wire('modules')->get("MarkupAdminDataTable");
$table->setEncodeEntities(false);
$table->setCaption('<p class="description"><i class="fa fa-floppy-o" aria-hidden="true"></i> '.
'means that content was only saved, you can edit it and send, or delete<br>' .
'<i class="fa fa-envelope-o" aria-hidden="true"></i> '.
'means that newsletter was sent, you can use its content to create new one.</p>');
$table->headerRow( ["Subject", "Date", "To", "Total sent", "Template", "Author", "Actions"] );
$pageArr = $this->wire('page')->children("sort=-modified, limit=50");
$pagination = $pageArr->renderPager();
foreach($pageArr as $p){
//details are stored as a plain text devided by ## in such an order
//sent to, total sent, used template, status
//it changes the icon and available actions
$arr = explode("##", $p->get($this->fieldDetails));
$url = $this->wire('page')->url . "loadPage/?pageName=" . $p->name;
if (!isset($arr[3])) continue;
switch ($arr[3]) {
case self::$status['SENT']:
$icon = '<i class="fa fa-envelope-o" aria-hidden="true"></i> ';
$edit = '<a href="'.$url.'&createNew=1" title="Re-use its content"><i class="fa fa-undo"></i></a>';
break;
case self::$status['SAVED']:
$icon = '<i class="fa fa-floppy-o" aria-hidden="true"></i> ';
$edit = '<a href="'.$url.'" title="Edit and send"><i class="fa fa-pencil-square-o"></i></a>';
break;
case self::$status['ERROR']:
$icon = '<i class="fa fa-flash" aria-hidden="true"></i> ';
$edit = '<a href="'.$url.'" title="Edit and send"><i class="fa fa-pencil-square-o"></i></a>';
break;
default:
$icon = "";
$edit = "";
}
//append preview button
$url = $this->wire('page')->url . "showDetails/?detailsPageName=" . $p->name . "&modal=1";
$edit .= ' <a class="NewsletterDetails" href="'.$url.'" title="Show details"><i class="fa fa-binoculars"></i></a>';
//append delete button but do not allow to trash current page and sent newsletters
if ($p->name !== $this->pageName && $arr[3] !== self::$status['SENT']) {
$url = $this->wire('page')->url . "trashPage/?trashPageName=" . $p->name;
$edit .= ' <a class="NewsletterTrashPage" href="'.$url.'" title="Delete"><i class="fa fa-trash-o"></i></a>';
}
$data = array(
$icon . ($p->title ? $p->title : "<i>Untitled</i>"),
date("F j, Y", $p->modified),
$arr[0],
$arr[1],
$arr[2],
$p->modifiedUser->name,
$edit
);
$table->row($data);
}
//add button to create empty newsletter
$table->action(array(
'New' => wire('page')->url,
));
$table = $table->render() . $pagination;
$f = $this->modules->get('InputfieldMarkup');
$f->attr('name', 'newsletter_history');
$f->value = $table;
$tab->add($f);
$form->add($tab);
if ($this->modules->isInstalled('Subscribers')) {
//third tab - subscribers
$tab = new InputfieldWrapper();
$tab->attr('title', $this->_('Subscribers'));
$id = $this->className() . 'Subscribers';
$tab->attr('id', $id);
$tab->class .= ' WireTab';
$f = $this->modules->get('InputfieldMarkup');
$f->label = '';
$f->attr('name', 'subscribersList');
$subscribers = wire('modules')->get('Subscribers');
$f->attr('value', $subscribers->renderSubscribersList());
$tab->add($f);
$fset = $this->modules->get('InputfieldFieldset');
$fset->label = $this->_('Import/Export');
$id = $this->className() . 'import';
$fset->attr('id', $id);
$fset->collapsed = Inputfield::collapsedYes;
$f = $this->modules->get('InputfieldTextarea');
$f->attr('name', 'subscribersCsv');
$f->attr('value', '');
$f->label = $this->_('Import subscribers');
$f->description = "Paste emails to import, each in a new line";
$f->attr('rows', 5);
$f->collapsed = 5;
$fset->add($f);
$f = $this->modules->get('InputfieldSubmit');
$f->attr('name', 'submit_import');
$f->attr('value', $this->_('Import'));
$f->icon = 'cloud-upload';
$fset->add($f);
$f = $this->modules->get('InputfieldSubmit');
$f->attr('name', 'submit_export');
$f->attr('value', $this->_('Export'));
$f->icon = 'download';
$fset->add($f);
$tab->add($fset);
$form->add($tab);
}
if (wire('user')->hasPermission('logs-view') ) {
//fourth tab - logs
$tab = new InputfieldWrapper();
$tab->attr('title', $this->_('Logs'));
$id = $this->className() . 'logs';
$tab->attr('id', $id);
$tab->class .= ' WireTab';
$logs = wire('log')->getEntries($this->log);
$table = wire('modules')->get("MarkupAdminDataTable");
$table->headerRow( ["Date/Time", "User","Message"]);
foreach ($logs as $log ) {
$table->row(array($log['date'] , $log['user'],$log['text'] ));
}
$f = $this->modules->get('InputfieldMarkup');
$f->label = 'Newsletter logs';
$f->attr('name', 'newsletterLogs');
$f->attr('value', $table->render());
$tab->add($f);
$form->add($tab);
}
return $form;
}
/**
* render newslleter form
*
*/
protected function renderNewsletter() {
$form = $this->buildForm();
$note = "<p class='detail'>" . "</p>";
return $form->render() . $note;
}
public function ___execute() {
if (!$this->setup()) return;
$this->fuel('breadcrumbs')->add(new Breadcrumb("./", "Send Newsletter"));
if ($this->input->post('submit_send')) {
$this->fillFields();
$out = $this->processSend(false);
return $out;
} else if ($this->input->post('submit_test')) {
$this->fillFields();
$out = $this->processSend(true);
return $out;
} else if ($this->input->post('submit_save')) {
$this->fillFields();
$this->saveNewsletterPage(self::$status['SAVED']);
$this->message($this->_("Newsletter was saved."));
$this->session->redirect($this->page->url . "LoadPage/?pageName=".$this->pageName);
} else if ($this->input->post('submit_import')) {
return $this->executeImport();
}if ($this->input->post('submit_export')) {
return $this->executeExport();
} else {
return $this->renderNewsletter();
}
}
/**
* Preview newsletter to be sent
*
*/
public function executePreview() {
if ($this->input->get('preview')) {
$this->fillFields();
return $this->renderNewsletterPreview($this->input->get('template'),
$this->input->get('title'));
}
}
/**
* Fired on select template change
*
*/
public function executeTemplatePreview() {
if ($this->input->post('templateName')) {
return $this->getTemplateImage($this->input->post('templateName'));
}
}
/**
* Move page to trash
*
*/
public function executeTrashPage() {
if ($this->input->get('trashPageName')) {
$this->deletePage($this->input->get('trashPageName'));
return 'true';
}
}
/**
* load saved newsletter
*
*/
public function executeLoadPage() {
if ($this->input->get('pageName')) {
$this->loadSavedPage($this->input->get('pageName'));
//prevent form resaving at the same name
if ($this->input->get('createNew')) {
$this->pageName = 0;
}
return $this->renderNewsletter();
}
}
/**
* Show sent newsletter details
*
*/
public function executeShowDetails() {
if ($this->input->get('detailsPageName')) {
return $this->showPageDetails($this->input->get('detailsPageName'));
}
}
public function executeImport() {
if ($this->input->post('subscribersCsv')) {
$subscribers = wire('modules')->get('Subscribers');
return $subscribers->importSubscribers($this->input->post('subscribersCsv'));
}
}
public function executeExport() {
$subscribers = wire('modules')->get('Subscribers');
return $subscribers->exportToCsv(false);
}
/**
* Save inputs to variables
*
*/
protected function fillFields() {
$this->title = ($this->input->post('newsletter_title') ?
$this->input->post->text('newsletter_title') : $this->input->get->text('newsletter_title') );
$this->body = ($this->input->post('newsletter_body') ?
$this->input->post->purify('newsletter_body') : $this->input->get->purify('newsletter_body') );
$this->actionText = ($this->input->post('newsletter_button_text') ?
$this->input->post->text('newsletter_button_text') : $this->input->get->text('newsletter_button_text') );
$this->actionLink = ($this->input->post('newsletter_button_link') ?
$this->input->post->url('newsletter_button_link') : $this->input->get->url('newsletter_button_link') );
$this->template = ($this->input->post('newsletter_template') ?
$this->input->post->text('newsletter_template') : $this->input->get->text('newsletter_template') );
$this->newsletterGroup = ($this->input->post('newsletter_group') ?
$this->input->post->text('newsletter_group') : $this->input->get->text('newsletter_group') );
$this->pageName = ($this->input->post('newsletter_page_name') ?
$this->input->post->pageName('newsletter_page_name') : $this->input->get->pageName('newsletter_page_name') );
}
/**
* Merge template with a text and send newsletter using provided backend
* @param bool $test whether email should be sent only to the current user
*
*/
protected function processSend($test = true) {
//recipients can be in one or many groups
if ($this->wire('input')->post('newsletter_group') === 'all' ) {
$roles = implode("|", $this->config('receiverRole'));
} else {
$roles = $this->wire('input')->post('newsletter_group');
}
if ($test) {
$recipients = $this->users->find("email=". $this->user->email);
} else {
$recipients = $this->wire('users')->find("roles=" . $roles . ", email!=''");
}
$subscribers = array();
//create array of subscribers and links to unsubscribe
foreach ($recipients as $recipient) {
$r = array('email' => $recipient->email,
'link' => $recipient[$this->config('unsubscribeUrl')],
'name' => ($this->config('useNames') ? $recipient->name : "" )
);
$subscribers[] = $r;
}
if (!count($subscribers)) {
$this->error("Subscribers list is empty, nothing to do.");
$this->fillFields();
return $this->renderNewsletter();
}
//prepare text to be sent
$plain = $this->fillTemplateToPlain();
$html = $this->fillHTMLTemplate();
//call a send backend
$file = dirname( __FILE__ ) . "/" . $this->config('backend');
if (!file_exists($file)) return "Unable to find backend file.";
require($file);
if (!function_exists('send')) return "Provided backend file is corrupted.";
$credentials = array('name' => $this->config('fromName'),
'email' => $this->config('fromEmail'),
'pass' => $this->config('backendPass'));
$result = send($this->title, $html, $plain, $subscribers, $credentials);
//in test case go back to the same page
if ($test) {
if ($result === true) {
$this->message("Test message was sent to you at " . $this->user->email);
} else {
$this->error("Error sending newsletter: " .$result);
$this->wire('log')->save($this->log, "TEST Error: $result");
}
$this->fillFields();
return $this->renderNewsletter();
}
if ($result !== true) {
$this->saveNewsletterPage(self::$status['ERROR']);
$this->wire('log')->save($this->log, "ERROR: $result");
return $this->_("<h2>Error sending newsletter </h2>") .$result;
}
$this->saveNewsletterPage(self::$status['SENT']);
$this->wire('log')->save($this->log, "SENT: {$this->title}");
return $this->_("<h2>Sent successfully to subscribers</h2>");
}
/**
* Fill html template with user input
* @return string html ready to send, but backend must fill unsubscribe link (different for every reciepient)
*
*/
protected function fillHTMLTemplate() {
//return true;
$file = dirname( __FILE__ ) . "/templates/" . $this->wire('input')->post('newsletter_template');
if (!file_exists($file)) return "Unable to find template file.";
$html = file_get_contents($file, false);
//perform substitution
return $this->substitute($html);
}
/**
* Substitute template variable with user input and convert plain body to html
* @return string html ready to send, but backend must fill unsubscribe link (different for every reciepient)
*
*/
protected function substitute($html) {
require_once(dirname( __FILE__ ) .'/textformatters.php');
$msg = convertBreaks($this->body);
$html = str_replace("{{HEADER}}", $this->config('header'), $html);
$html = str_replace("{{TITLE}}", $this->title, $html);
$html = str_replace("{{CONTENT}}", $msg, $html);
$html = str_replace("{{ACTION-LINK}}", $this->actionLink, $html);
$html = str_replace("{{ACTION-TEXT}}", $this->actionText, $html);
$html = str_replace("{{FOOTER}}", $this->config('footer'), $html);
$html = str_replace("{{UNSUBSCRIBE}}", $this->config('unsubscribeText'), $html);
return $html;
}
/**
* Fill template with user input and convert to plain text
* @return string plain text ready to send, but backend must fill unsubscribe link (different for every reciepient)
*
*/
protected function fillTemplateToPlain() {
$actionText = $this->actionText . " " . $this->actionLink;
$body = trim(preg_replace('/(\s)\s+/', '$1', $this->body));
$plain = $this->config('header') . "\n\n" .$this->title . "\n\n" . $body ."\n\n" . $actionText . "\n\n\n"
. $this->config('footer') . "\n" . $this->config('unsubscribeText') . " {{LINK}}";
return $this->sanitizer->textarea($plain);
}
/**
* Save newsletter as a page
*
*/
protected function saveNewsletterPage($status) {
if ($this->wire('input')->post('newsletter_group') === 'all' ) {
$roles = implode("|", $this->config('receiverRole'));
} else {
$roles = $this->wire('input')->post('newsletter_group');
}
//save total sent messages number
$count = ($status !== self::$status['SENT'] ? "-" : $this->wire('users')->count("roles=" . $roles . ", email!=''"));
//details are just string with sent to group(s) ## amount of sent msgs ## template name
$details = $this->input->post('newsletter_group') . "##"
. $count . "##"
. str_replace(".html", "", $this->input->post('newsletter_template')) . "##"
. $status;
if ($this->pageName == "") {
$p = new Page();
$p->template = $this->templateName;
$p->parent = $this->wire('page');
$p->name = $this->sanitizer->pageName($this->title . '_'.time());
$p->title = $this->title;
$p->save();
$this->pageName = $p->name;
} else {
$p = $this->pages->get("name=".$this->pageName);
$p->title = $this->title;
}
$p->of(false);
$p->set($this->fieldBody, $this->body);
$p->set($this->fieldDetails, $details);
$p->set($this->fieldActionButton, $this->actionText . "##" . $this->actionLink);
$p->save();
}
/**
* Get template preview image, it assumes the image has the same name and .jpg format
*
* @param string $templateFileName name of the template file
* @return string url to image or empty string if not found
*
*/
protected function getTemplateImage($templateFileName) {
$file = dirname( __FILE__ ) . "/templates/" . str_replace(".html", ".jpg", $templateFileName);
$url = $this->config->urls->siteModules . "ProcessSendNewsletter" . "/templates/" . str_replace(".html", ".jpg", $templateFileName);
if (!file_exists($file)) return "";
return $url;
}
/**
* Render email template preview and return string with markup
*
* @param string $templateFileName name of the template file
* @return string html markup with template
*
*/
protected function renderTemplatePreview($templateFileName) {
$file = dirname( __FILE__ ) . "/templates/" . $templateFileName;
if (!file_exists($file)) return "Unable to find template file.";
return file_get_contents($file, false);
}
/**
* Render newsletter preview and return string with markup
*
* @param string $templateFileName name of the template file
* @return string html markup with template
*
*/
protected function renderNewsletterPreview($templateFileName) {
$html = $this->renderTemplatePreview($templateFileName);
return $this->substitute($html);
}
/**
* Read saved page and translate it to newsletter form fields
*
* @param string $pageName name of a saved page
*
*/
protected function loadSavedPage($pageName) {
$this->pageName = $pageName;
$p = $this->wire('pages')->get("name=".$pageName);
$this->title = $p->title;
$this->body = $p->get($this->fieldBody);
$action = explode('##', $p->get($this->fieldActionButton));
$this->actionText = $action[0];
$this->actionLink = $action[1];
//0 - group, 1 - number, 2 - template, 3 - status
$details = explode('##', $p->get($this->fieldDetails));
$this->template = $details[2];
$this->newsletterGroup = $details[0];
}
/**
* Move given page to a trash
*
* @param string $pageName name of a saved page
*
*/
protected function deletePage($pageName) {
$p = $this->wire('pages')->get("name=".$pageName);
$p->delete();
}
/**
* Show details about saved page/newsletter
*
* @param string $pageName name of a saved page
*
*/
protected function showPageDetails($pageName) {
$this->loadSavedPage($pageName);
$html = $this->renderNewsletterPreview($this->template.".html");
$p = $this->wire('pages')->get("name=".$pageName);
$date = date($this->config->dateFormat, $p->created);
$out = "<p class='notes'>This newsletter was created by {$p->createdUser->name} on {$date}</p>";
return $out. $html;
}
/**
* Install ProcessSendNewsletter
*
*/
public function ___install() {
if(version_compare($this->wire('config')->version, self::minVersion , '<')) {
throw new WireException("This module requires ProcessWire " . self::minVersion . " or newer.");
}
$permission = $this->permissions->get('newsletter-sender');
if (!$permission->id) {
$p = new Permission();
$p->name = 'newsletter-sender';
$p->title = $this->_('Can send newsletter');
$p->save();
$this->message('Created new permission: newsletter-sender');
}
$role = $this->roles->get('newsletter');
if (!$role->id) {
$p = new Role();
$p->name = 'newsletter';
$p->title = $this->_('Will receive newsletters');
$p->save();
$this->message('Created new role: newsletter');
}
//create fields and template
$field = $this->fields->get($this->fieldBody);
if (!$field->id) {
$f = new Field();
$f->type = $this->modules->get('FieldtypeTextarea');
$f->name = $this->fieldBody;
$f->label = "Newsletter body text";
$f->description = "The field stores text of a sent newsletter";
$f->collapsed = 5;
$f->rows = 10;
$f->save();
}
$field = $this->fields->get($this->fieldActionButton);
if (!$field->id) {
$f = new Field();
$f->type = $this->modules->get('FieldtypeText');
$f->name = $this->fieldActionButton;
$f->label = "Newsletter action button text and url";
$f->description = "The field stores info about a sent newsletter";
$f->collapsed = 5;
$f->save();
}
$field = $this->fields->get($this->fieldDetails);
if (!$field->id) {
$f = new Field();
$f->type = $this->modules->get('FieldtypeTextarea');
$f->name = $this->fieldDetails;
$f->label = "Newsletter details";
$f->description = "The field stores info about a sent newsletter";
$f->collapsed = 5;
$f->rows = 10;
$f->save();
}
$fg = new Fieldgroup();
$fg->name = $this->templateName;
$fg->add($this->fieldBody);
$fg->add($this->fieldDetails);
$fg->add($this->fieldActionButton);
$fg->add("title");
$fg->save();
// create a new template to use with this fieldgroup
$temp = $this->fields->get($this->templateName);
if (!$temp->id) {
$t = new Template();
$t->name = $this->templateName;
$t->fieldgroup = $fg;
$t->label = 'SendNewsletter';
$t->noChildren = 1;// the pages using this template should not have children
$t->save();
}
$this->message('Created Template: SendNewsletter');
parent::___install();
}
/**
* Uninstall module
*
*/
public function ___uninstall() {
//delete all newsletter pages, also those in a trash
$moduleID = $this->modules->getModuleID($this);
$page = $this->pages->get("template=admin, process=$moduleID");
$this->wire('pages')->delete($page, true);
foreach ($this->wire('pages')->find('template='.$this->templateName .', status>=' . Page::statusTrash) as $p) $p->delete();
// find and delete the permission
$permission = $this->permissions->get('newsletter-sender');
if ($permission->id){
$permission->delete();
$this->message('Deleted Permission: newsletter-sender');
}
// find and delete the template
$t = $this->wire('templates')->get($this->templateName);
if ($t->id) {
$this->wire('templates')->delete($t);
$this->wire('fieldgroups')->delete($t->fieldgroup);// delete the associated fieldgroups
$this->message('Deleted Template: ' . $this->templateName);
}
// find and delete the created fields
$fields = array($this->fieldBody, $this->fieldActionButton, $this->fieldDetails);
foreach ($fields as $field) {
$f = $this->wire('fields')->get($field);
if($f->id) $this->wire('fields')->delete($f);
$this->message('Deleted created fields');
}
parent::___uninstall();
}
static public function getModuleConfigInputfields(array $data) {
$data = array_merge(self::$defaults, $data);
$fields = new InputfieldWrapper();
$modules = wire('modules');
$field = $modules->get('InputfieldTextarea');
$field->attr('name', 'header');
$field->attr('rows', 5);
$field->attr('value', $data['header']);
$field->label = 'Header you can add to every newsletter.';
$field->notes = 'You can use {{NAME}} and {{EMAIL}} to personalise.';
$field->columnWidth = 50;
$fields->append($field);
$field = $modules->get('InputfieldTextarea');
$field->attr('name', 'footer');
$field->attr('rows', 5);
$field->attr('value', $data['footer']);
$field->label = 'Footer added to every newsletter.';
$field->notes = 'You can use {{NAME}} and {{EMAIL}} to personalise.';
$field->columnWidth = 50;
$fields->append($field);
$field = $modules->get('InputfieldText');
$field->attr('name', 'unsubscribeText');
$field->attr('size', 0);
$field->attr('value', $data['unsubscribeText']);
$field->label = 'Description of an unsubscribe link';
$field->columnWidth = 50;
$fields->append($field);
$field = $modules->get('InputfieldSelect');
$field->attr('name', 'unsubscribeUrl');
$field->attr('size', 0);
$field->attr('value', $data['unsubscribeUrl']);
$field->label = 'Field from user template that stores unsubscribe link';
$roles = wire('roles')->find('sort=name');
//get user template's fields
$items = wire('templates')->get('user')->fields;
foreach ($items as $f) {
$field->addOption($f->name);
}
$field->columnWidth = 50;
$field->required = true;
$fields->append($field);
$field = $modules->get('InputfieldSelectMultiple');
$field->attr('name', 'receiverRole');
$field->attr('size', 0);
$field->attr('value', $data['receiverRole']);
$field->label = 'User role to receive newsletter';
$roles = wire('roles')->find('sort=name');
foreach ($roles as $r) {
$field->addOption($r->name);
}
$field->columnWidth = 50;
$field->required = true;
$fields->append($field);
$field = $modules->get('InputfieldSelect');
$field->attr('name', 'senderRole');
$field->attr('size', 0);
$field->attr('value', $data['senderRole']);
$field->label = 'User role able to send newsletter';
$field->notes = "Or anyone having 'newsletter-sender' permission";
$roles = wire('roles')->find('sort=name');
foreach ($roles as $r) {
$field->addOption($r->name);
}
$field->columnWidth = 50;
$fields->append($field);
$field = $modules->get('InputfieldCheckbox');
$field->attr('name', 'useNames');
$field->attr('size', 0);
$field->attr('checked', $data['useNames']);
$field->label = 'Allow for subscribers names in newsletters';