-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews_send.module
1054 lines (951 loc) · 34.7 KB
/
views_send.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
/**
* @file
* The Views Send module.
*
* Views Send allow mass mailing using Views.
*
* @ingroup views_send
*/
use \Drupal\Component\Utility\Unicode;
use \Drupal\Component\Utility\UrlHelper;
use \Drupal\Core\Url;
use \Drupal\Core\Mail\MailFormatHelper;
use \Drupal\Component\Utility\Html;
use \Drupal\filter\Entity\FilterFormat;
use \Drupal\views_send\Event\AllMailAddedEvent;
use \Drupal\views_send\Event\MailAddedEvent;
use \Drupal\views_send\Event\MailSentEvent;
/**
* e-mail priorities.
*/
define('VIEWS_SEND_PRIORITY_NONE', 0);
define('VIEWS_SEND_PRIORITY_HIGHEST', 1);
define('VIEWS_SEND_PRIORITY_HIGH', 2);
define('VIEWS_SEND_PRIORITY_NORMAL', 3);
define('VIEWS_SEND_PRIORITY_LOW', 4);
define('VIEWS_SEND_PRIORITY_LOWEST', 5);
/**
* Capture PHP max_execution_time before drupal_cron_run().
* Workaround for Drupal 6.14. See http://drupal.org/node/584334
*/
define('VIEWS_SEND_MAX_EXECUTION_TIME', ini_get('max_execution_time'));
/**
* Token pattern.
*/
define('VIEWS_SEND_TOKEN_PATTERN', 'views-send:%s');
define('VIEWS_SEND_TOKEN_PREFIX', '[');
define('VIEWS_SEND_TOKEN_POSTFIX', ']');
/**
* Detect and store Mime Mail module presence.
*/
define('VIEWS_SEND_MIMEMAIL', \Drupal::moduleHandler()->moduleExists('mimemail'));
/**
* Gets the selector field if it exists on the passed-in view.
*
* @return
* The field object if found. Otherwise, FALSE.
*/
function _views_send_get_field($view) {
foreach ($view->field as $field_name => $field) {
if ($field instanceof Drupal\views_send\Plugin\views\field\ViewsSend) {
// Add in the view object for convenience.
$field->view = $view;
return $field;
}
}
return FALSE;
}
/**
* Implements the form for the "configure" step.
*
* @param \Drupal\views\ViewExecutable $view
* Viewexecutable object.
*/
function views_send_config_form(&$form, &$form_state, $view) {
$display = $view->storage->id() . ':' . $view->current_display;
$form['display'] = array(
'#type' => 'value',
'#value' => $display,
);
$form['from'] = array(
'#type' => 'details',
'#title' => t('Sender'),
'#open' => TRUE,
);
$config_basekey = $display . '.uid:' . \Drupal::currentUser()->id();
$site_config = \Drupal::config('system.site');
$config = \Drupal::config('views_send.user_settings')->get($config_basekey);
$form['from']['views_send_from_name'] = array(
'#type' => 'textfield',
'#title' => t('Sender\'s name'),
'#description' => t("Enter the sender's human readable name."),
'#default_value' => isset($config['from_name']) ? $config['from_name'] : $site_config->get('name'),
'#maxlen' => 255,
);
$form['from']['views_send_from_mail'] = array(
'#type' => 'textfield',
'#title' => t('Sender\'s e-mail'),
'#description' => t("Enter the sender's e-mail address."),
'#required' => TRUE,
'#default_value' => isset($config['from_mail']) ? $config['from_mail'] : $site_config->get('mail'),
'#maxlen' => 255,
);
$fields = _views_send_get_fields_and_tokens($view, 'fields');
$tokens = _views_send_get_fields_and_tokens($view, 'tokens');
$fields_name_text = _views_send_get_fields_and_tokens($view, 'fields_name_text');
$fields_options = array_merge(array('' => '<' . t('select') . '>'), $fields);
$form['views_send_tokens'] = array(
'#type' => 'value',
'#value' => $tokens,
);
$form['to'] = array(
'#type' => 'details',
'#title' => t('Recipients'),
'#open' => TRUE,
);
$form['to']['views_send_to_name'] = array(
'#type' => 'select',
'#title' => t('Field used for recipient\'s name'),
'#description' => t('Select which field from the current view will be used as recipient\'s name.'),
'#options' => $fields_options,
'#default_value' => isset($config['to_name']) ? $config['to_name'] : '',
);
$form['to']['views_send_to_mail'] = array(
'#type' => 'select',
'#title' => t('Field used for recipient\'s e-mail'),
'#description' => t('Select which field from the current view will be used as recipient\'s e-mail.'),
'#options' => $fields_options,
'#default_value' => isset($config['to_mail']) ? $config['to_mail'] : '',
'#required' => TRUE,
);
$form['mail'] = array(
'#type' => 'details',
'#title' => t('E-mail content'),
'#open' => TRUE,
);
$form['mail']['views_send_subject'] = array(
'#type' => 'textfield',
'#title' => t('Subject'),
'#description' => t('Enter the e-mail\'s subject. You can use tokens in the subject.'),
'#maxlen' => 255,
'#required' => TRUE,
'#default_value' => isset($config['subject']) ? $config['subject'] : '',
);
$saved_message = isset($config['message']) ? $config['message'] : array();
$form['mail']['views_send_message'] = array(
'#type' => 'text_format',
'#format' => isset($saved_message['format']) ? $saved_message['format'] : 'plain_text',
'#title' => t('Message'),
'#description' => t('Enter the body of the message. You can use tokens in the message.'),
'#required' => TRUE,
'#rows' => 10,
'#default_value' => isset($saved_message['value']) ? $saved_message['value'] : '',
);
$form['mail']['token'] = array(
'#type' => 'details',
'#title' => t('Replacements'),
'#description' => t('You can use the following tokens in the subject or message.'),
);
if (!\Drupal::moduleHandler()->moduleExists('token')) {
$form['mail']['token']['tokens'] = array(
'#markup' => views_send_token_help($fields_name_text)
);
}
else {
$form['mail']['token']['views_send'] = array(
'#type' => 'details',
'#title' => t('Views Send specific tokens'),
);
$form['mail']['token']['views_send']['tokens'] = array(
'#markup' => views_send_token_help($fields_name_text)
);
$form['mail']['token']['general'] = array(
'#type' => 'details',
'#title' => t('General tokens'),
);
$token_types = array('site', 'user', 'node', 'current-date');
$form['mail']['token']['general']['tokens'] = array(
'#theme' => 'token_tree_link',
'#token_types' => $token_types,
);
}
if (VIEWS_SEND_MIMEMAIL && Drupal::currentUser()->hasPermission('attachments with views_send')) {
// set the form encoding type
$form['#attributes']['enctype'] = "multipart/form-data";
// add a file upload file
$form['mail']['views_send_attachments'] = array(
'#type' => 'file',
'#title' => t('Attachment'),
'#description' => t('NB! The attached file is stored once per recipient in the database if you aren\'t sending the message directly.'),
);
}
$form['additional'] = array(
'#type' => 'details',
'#title' => t('Additional e-mail options'),
);
$form['additional']['views_send_priority'] = array(
'#type' => 'select',
'#title' => t('Priority'),
'#options' => array(
VIEWS_SEND_PRIORITY_NONE => t('none'),
VIEWS_SEND_PRIORITY_HIGHEST => t('highest'),
VIEWS_SEND_PRIORITY_HIGH => t('high'),
VIEWS_SEND_PRIORITY_NORMAL => t('normal'),
VIEWS_SEND_PRIORITY_LOW => t('low'),
VIEWS_SEND_PRIORITY_LOWEST => t('lowest')
),
'#description' => t('Note that e-mail priority is ignored by a lot of e-mail programs.'),
'#default_value' => isset($config['priority']) ? $config['priority'] : 0,
);
$form['additional']['views_send_receipt'] = array(
'#type' => 'checkbox',
'#title' => t('Request receipt'),
'#default_value' => isset($config['receipt']) ? $config['receipt'] : 0,
'#description' => t('Request a Read Receipt from your e-mails. A lot of e-mail programs ignore these so it is not a definitive indication of how many people have read your message.'),
);
$form['additional']['views_send_headers'] = array(
'#type' => 'textarea',
'#title' => t('Additional headers'),
'#description' => t("Additional headers to be send with the message. You'll have to enter one per line. Example:<pre>Reply-To: [email protected]\nX-MyCustomHeader: Whatever</pre>"),
'#rows' => 4,
'#default_value' => isset($config['headers']) ? $config['headers'] : '',
);
$form['views_send_direct'] = array(
'#type' => 'checkbox',
'#title' => t('Send the message directly using the Batch API.'),
'#default_value' => isset($config['direct']) ? $config['direct'] : TRUE,
);
$form['views_send_carbon_copy'] = array(
'#type' => 'checkbox',
'#title' => t('Send a copy of the message to the sender.'),
'#default_value' => isset($config['carbon_copy']) ? $config['carbon_copy'] : TRUE,
);
$form['views_send_remember'] = array(
'#type' => 'checkbox',
'#title' => t('Remember these values for the next time a mass mail is sent.'),
'#default_value' => isset($config['remember']) ? $config['remember'] : FALSE,
);
$query = UrlHelper::filterQueryParameters($_GET, array('q'));
$url = $view->getUrl()->setOption('query', $query);
$form['actions'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('form-actions')),
'#weight' => 999,
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Next'),
'#validate' => array('views_send_config_form_validate'),
'#suffix' => \Drupal::l(t('Cancel'), $url),
);
return $form;
}
/**
* Validation callback for the "configure" step.
*/
function views_send_config_form_validate($form, &$form_state) {
$account = Drupal::currentUser();
$values = $form_state->getValues();
$build_info = $form_state->getBuildInfo();
/** @var \Drupal\views\ViewExecutable $view */
$view = $build_info['args'][0];
if (!$format = FilterFormat::load($values['views_send_message']['format'])) {
$form_state->setErrorByName('views_send_message', t('Non-existsing format selected'));
}
elseif (!$format->access('use', $account)) {
$form_state->setErrorByName('views_send_message', t('Illegale format selected'));
}
// Check if sender's e-mail is a valid one.
if (!valid_email_address(trim($values['views_send_from_mail']))) {
$form_state->setErrorByName('views_send_from_mail',
t('The sender\'s e-mail is not a valid e-mail address: %mail',
array('%mail' => $values['views_send_from_mail'])
)
);
}
// Check in the column selected as e-mail contain valid e-mail values.
if (!empty($values['views_send_to_mail'])) {
$wrong_addresses = array();
$to_mail_field = $values['views_send_tokens'][$values['views_send_to_mail']];
$selection = $form_state->get('selection');
$view_data = $form_state->get('view_data');
foreach ($selection as $row_id) {
$to_mail_rendered = $view_data[$row_id][$to_mail_field];
$to_mail_arr = explode(',', strip_tags($to_mail_rendered));
foreach ($to_mail_arr as $to_mail) {
$to_mail = trim($to_mail);
if (!valid_email_address($to_mail)) {
$wrong_addresses[$row_id] = $to_mail;
break;
}
}
}
if (count($wrong_addresses) > 0) {
if (count($wrong_addresses) == count($selection)) {
$error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in all selected rows. Maybe choose another field to act as recipient's e-mail?");
}
else {
$error_message = t("The field used for recipient's e-mail contains an invalid e-mail address in @wrong of @total selected rows. Choose another field to act as recipient's e-mail or return to the view and narrow the selection to a subset containing only valid addresses. Bad addresses:",
array('@wrong' => count($wrong_addresses), '@total' => count($selection))
);
$error_message .= sprintf('<table><tr><th>%s</th><th>%s</th></tr>',
t('Row'), t('E-mail address'));
foreach ($wrong_addresses as $rowid => $wrong_address) {
$error_message .= sprintf('<tr><td>%s</td><td>%s</td></tr>',
$rowid, Html::escape($wrong_address));
}
$error_message .= '</table>';
}
$form_state->setErrorByName('views_send_to_mail', $error_message);
}
}
}
/**
* Implements the form for the "confirm" step.
*
* Allows the user to preview the whole message before sending it.
*/
function views_send_confirm_form(&$form, &$form_state, $view) {
// TODO: Set title as #markup in stead.
$form['#title'] = Html::escape(t('Review and confirm the message that is about to be sent'));
// Values entered in the "config" step.
$configuration = $form_state->get('configuration');
$selection = $form_state->get('selection');
if (!VIEWS_SEND_MIMEMAIL && ($configuration['views_send_message']['format'] != 'plain_text')) {
drupal_set_message(t("Only plain text is supported in the message. Any HTML will be converted to text. If you want to format the message with HTML, you'll have to install and enable the <a href=':url'>Mime Mail</a> module.",
array(':url' => 'http://drupal.org/project/mimemail'))
);
}
// From: parts.
$from_mail = trim($configuration['views_send_from_mail']);
$from_name = trim($configuration['views_send_from_name']);
$form['#attributes']['class'] = array('views-send-preview');
$form['from'] = array(
'#type' => 'item',
'#title' => t('From'),
'#markup' => '<div class="views-send-preview-value">' .
Html::escape(_views_send_format_address($from_mail, $from_name, FALSE)) .
'</div>',
);
$recipients = array();
$to_name_field = $configuration['views_send_tokens'][$configuration['views_send_to_name']];
$to_mail_field = $configuration['views_send_tokens'][$configuration['views_send_to_mail']];
$view_data = $form_state->get('view_data');
foreach ($selection as $row_id) {
$to_name = strip_tags($view_data[$row_id][$to_name_field]);
$to_mail_rendered = $view_data[$row_id][$to_mail_field];
$to_mail_arr = explode(',', strip_tags($to_mail_rendered));
foreach ($to_mail_arr as $to_mail) {
$recipients[] = Html::escape(_views_send_format_address($to_mail, $to_name, FALSE));
}
}
$form['to'] = array(
'#type' => 'item',
'#title' => t('To'),
'#markup' => '<div id="views-send-preview-to" class="views-send-preview-value">' . implode(', ', $recipients) . '</div>',
);
$form['subject'] = array(
'#type' => 'item',
'#title' => t('Subject'),
'#markup' => '<div class="views-send-preview-value">' . Html::escape($configuration['views_send_subject']) . '</div>',
);
$form['message'] = array(
'#type' => 'item',
'#title' => t('Message'),
'#markup' => '<div id="views-send-preview-message" class="views-send-preview-value">' . check_markup($configuration['views_send_message']['value'], $configuration['views_send_message']['format']) . '</div>',
);
$headers = array();
foreach (_views_send_headers($configuration['views_send_receipt'], $configuration['views_send_priority'], $configuration['views_send_from_mail'], $configuration['views_send_headers']) as $key => $value) {
$headers[] = Html::escape($key . ': ' . $value);
}
$form['headers'] = array(
'#type' => 'item',
'#title' => t('Headers'),
'#markup' => '<div id="views-send-preview-headers" class="views-send-preview-value">' . implode('<br />', $headers) . '</div>',
);
if (VIEWS_SEND_MIMEMAIL && !empty($configuration['views_send_attachments']) && Drupal::currentUser()->hasPermission('attachments with views_send')) {
foreach ($configuration['views_send_attachments'] as $attachment) {
$attachments[] = Html::escape($attachment['filename']);
}
$form['attachments'] = array(
'#type' => 'item',
'#title' => t('Attachments'),
'#markup' => '<div id="views-send-preview-attachments" class="views-send-preview-value">'. implode('<br />', $attachments) .'</div>',
);
}
$query = UrlHelper::filterQueryParameters($_GET, array('q'));
$url = $view->getUrl()->setOption('query', $query);
$form['actions'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('form-actions')),
'#weight' => 999,
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => t('Send'),
'#suffix' => \Drupal::l(t('Cancel'), $url),
);
return $form;
}
/**
* Assembles the email and queues it for sending.
*
* @param $params
* Data entered in the "config" step of the form.
* @param $selected_rows
* An array with the indexes of the selected views rows.
* @param $view
* The actual view objecy.
*/
function views_send_queue_mail($params, $selected_rows, $view) {
$account = Drupal::currentUser();
if (!$account->hasPermission('mass mailing with views_send')) {
drupal_set_message(
t('No mails sent since you aren\'t allowed to send mass mail with Views. (<a href="@permurl">Edit the permission.</a>)',
array('@permurl' => url('admin/people/permissions', array('fragment' => 'module-views_send')))),
'error'
);
return;
}
$formats = filter_formats($account);
// From: parts.
$from_mail = trim($params['views_send_from_mail']);
$from_name = $params['views_send_from_name'];
$to_mail_key = $params['views_send_tokens'][$params['views_send_to_mail']];
$to_name_key = $params['views_send_tokens'][$params['views_send_to_name']];
foreach ($selected_rows as $row_id) {
// To: parts.
$to_mail = trim(strip_tags($view->style_plugin->getField($row_id, $to_mail_key)));
$to_name = trim(strip_tags($view->style_plugin->getField($row_id, $to_name_key)));
$subject = $params['views_send_subject'];
$body = $params['views_send_message']['value'];
$params['format'] = $params['views_send_message']['format'];
// This shouldn't happen, but better be 100% sure.
/* FIXME
if (!$formats[$params['format']]->access('use', $account)) {
drupal_set_message(t('No mails sent since an illegale format is selected for the message.'));
return;
}
*/
$body = check_markup($body, $params['format']);
// Populate row/context tokens.
$token_keys = $token_values = array();
foreach ($params['views_send_tokens'] as $field_key => $field_name) {
$token_keys[] = VIEWS_SEND_TOKEN_PREFIX . sprintf(VIEWS_SEND_TOKEN_PATTERN, $field_name) . VIEWS_SEND_TOKEN_POSTFIX;
$token_values[] = (string) $view->style_plugin->getField($row_id, $field_name);
}
// Views Send specific token replacements
$subject = str_replace($token_keys, $token_values, $subject);
$body = str_replace($token_keys, $token_values, $body);
// Global token replacement, and node/user token replacements
// if a nid/uid is found in the views result row.
$data = array();
if (property_exists($view->result[$row_id], 'uid')) {
$data['user'] = user_load($view->result[$row_id]->uid);
}
if (property_exists($view->result[$row_id], 'nid')) {
$data['node'] = node_load($view->result[$row_id]->nid);
}
$token_service = \Drupal::service('token');
$subject = $token_service->replace($subject, $data);
$body = $token_service->replace($body, $data);
if (!VIEWS_SEND_MIMEMAIL || (\Drupal::config('mimemail.settings')->get('format') == 'plain_text')) {
$body = MailFormatHelper::htmlToText($body);
}
if ($params['format'] == 'plain_text') {
$plain_format = TRUE;
}
else {
$plain_format = FALSE;
}
// We transform receipt, priority in headers,
// merging them to the user defined headers.
$headers = _views_send_headers($params['views_send_receipt'], $params['views_send_priority'], $from_mail, $params['views_send_headers']);
$attachments = isset($params['views_send_attachments']) ? $params['views_send_attachments'] : array();
$message = array(
'uid' => $account->id(),
'timestamp' => time(),
'from_name' => $from_name,
'from_mail' => $from_mail,
'to_name' => $to_name,
'to_mail' => $to_mail,
'subject' => strip_tags($subject),
'body' => $body,
'headers' => $headers,
);
if ($params['views_send_direct']) {
$operations[] = array('views_send_batch_deliver', array($message, $plain_format, $attachments));
}
else {
_views_send_prepare_mail($message, $plain_format, $attachments);
// Queue the message to the spool table.
db_insert('views_send_spool')->fields($message)->execute();
if (\Drupal::moduleHandler()->moduleExists('rules')) {
$event = new MailAddedEvent($message);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch(MailAddedEvent::EVENT_NAME, $event);
}
}
}
if ($params['views_send_direct']) {
if ($params['views_send_carbon_copy']) {
$message['to_name'] = $from_name;
$message['to_mail'] = $from_mail;
$operations[] = array('views_send_batch_deliver', array($message, $plain_format, $attachments));
}
$batch = array(
'operations' => $operations,
'finished' => 'views_send_batch_deliver_finished',
'progress_message' => t('Sent @current of @total messages.'),
);
batch_set($batch);
drupal_set_message(
\Drupal::translation()->formatPlural(count($selected_rows), '1 message processed.', '@count messages processed.')
);
}
else {
if ($params['views_send_carbon_copy']) {
$message['to_name'] = $from_name;
$message['to_mail'] = $from_mail;
db_insert('views_send_spool')->fields($message)->execute();
}
drupal_set_message(
\Drupal::translation()->formatPlural(count($selected_rows), '1 message added to the spool.', '@count messages added to the spool.')
);
if (\Drupal::moduleHandler()->moduleExists('rules')) {
$event = new AllMailAddedEvent(count($selected_rows));
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch(AllMailAddedEvent::EVENT_NAME, $event);
}
}
}
// === Hook implementations ====================================================
/**
* Implements hook_menu().
*/
function views_send_menu() {
$items = array();
$items['admin/config/system/views_send'] = array(
'type' => MENU_NORMAL_ITEM,
'title' => 'Views Send',
'description' => 'Configure Views Send general options.',
'route_name' => 'views_send.configure',
);
return $items;
}
/**
* Implements hook_theme().
*/
function views_send_theme($existing, $type, $theme, $path) {
return array(
'views_send_select_all' => array(
'variables' => array(),
),
);
}
/**
* Implements hook_cron().
*/
function views_send_cron() {
// Load cron functions.
module_load_include('cron.inc', 'views_send');
// Send pending messages from spool.
views_send_send_from_spool();
// Clear successful sent messages.
views_send_clear_spool();
}
/**
* Implements hook_mail().
*/
function views_send_mail($key, &$message, $params) {
// This is a simple message send. User inputs the content directly.
if ($key == 'direct') {
// Set the subject.
$message['subject'] = $params['subject'];
// Set the body.
$message['body'][] = $params['body'];
// Add additional headers.
$message['headers'] += $params['headers'];
}
// TODO: Implement node message parsing.
elseif ($key == 'node') {
// Translations, theming, etc...
}
}
// === Helper functions ========================================================
/**
* Build header array with priority and receipt confirmation settings.
*
* @param $receipt
* Boolean: If a receipt is requested.
* @param $priority
* Integer: The message priority.
* @param $from
* String: The sender's e-mail address.
*
* @return Header array with priority and receipt confirmation info
*/
function _views_send_headers($receipt, $priority, $from, $additional_headers) {
$headers = array();
// If receipt is requested, add headers.
if ($receipt) {
$headers['Disposition-Notification-To'] = $from;
$headers['X-Confirm-Reading-To'] = $from;
}
// Add priority if set.
switch ($priority) {
case VIEWS_SEND_PRIORITY_HIGHEST:
$headers['Priority'] = 'High';
$headers['X-Priority'] = '1';
$headers['X-MSMail-Priority'] = 'Highest';
break;
case VIEWS_SEND_PRIORITY_HIGH:
$headers['Priority'] = 'urgent';
$headers['X-Priority'] = '2';
$headers['X-MSMail-Priority'] = 'High';
break;
case VIEWS_SEND_PRIORITY_NORMAL:
$headers['Priority'] = 'normal';
$headers['X-Priority'] = '3';
$headers['X-MSMail-Priority'] = 'Normal';
break;
case VIEWS_SEND_PRIORITY_LOW:
$headers['Priority'] = 'non-urgent';
$headers['X-Priority'] = '4';
$headers['X-MSMail-Priority'] = 'Low';
break;
case VIEWS_SEND_PRIORITY_LOWEST:
$headers['Priority'] = 'non-urgent';
$headers['X-Priority'] = '5';
$headers['X-MSMail-Priority'] = 'Lowest';
break;
}
// Add general headers.
$headers['Precedence'] = 'bulk';
// Add additional headers.
$additional_headers = trim($additional_headers);
$additional_headers = str_replace("\r", "\n", $additional_headers);
$additional_headers = explode("\n", $additional_headers);
foreach ($additional_headers as $header) {
$header = trim($header);
if (!empty($header)) {
list($key, $value) = explode(': ', $header, 2);
$headers[$key] = trim($value);
}
}
return $headers;
}
/**
* Build a formatted e-mail address.
*/
function _views_send_format_address($mail, $name, $encode = TRUE) {
// Do not format addres on Windows based PHP systems or when $name is empty.
if ((substr(PHP_OS, 0, 3) == 'WIN') || empty($name)) {
return $mail;
}
else {
$name = ($encode ? Unicode::mimeHeaderEncode($name) : $name);
return sprintf('"%s" <%s>', $name, $mail);
}
}
/**
* Prepare the mail message before sending or spooling.
*
* @param array $message
* which contains the following keys:
* from_name
* String holding the Sender's name.
* from_mail
* String holding the Sender's e-mail.
* to_name
* String holding the Recipient's name.
* to_mail
* String holding the Recipient's e-mail.
* subject
* String with the e-mail subject. This argument can be altered here.
* body
* Text with the e-mail body. This argument can be altered here.
* headers
* Associative array with e-mail headers. This argument can be altered here.
* @param boolean $plain_format
* Whether the e-mail should be sent in plain format.
* @param array $attachments
* An array with file information objects (as returned by file_save_upload).
*/
function _views_send_prepare_mail(&$message, $plain_format=TRUE, $attachments=array()) {
// Extract all variables/keys from the message.
extract($message);
/**
* TODO: In the future, this module will be able to send an existing node.
* $key will have to make the difference. A value when we pickup a node, other
* when user inputs the subject & body of the message.
*/
$key = 'direct';
// Build message parameters.
$params = array();
$params['from_name'] = $from_name;
$params['from_mail'] = $from_mail;
$params['from_formatted'] = _views_send_format_address($from_mail, $from_name);
$params['to_name'] = $to_name;
$params['to_mail'] = $to_mail;
$to_mail_formatted = array();
foreach (explode(',', $to_mail) as $addr) {
$to_mail_formatted[] = _views_send_format_address($addr, $to_name);
}
$params['to_formatted'] = implode(', ', $to_mail_formatted);
$params['subject'] = $subject;
$params['body'] = $body;
$params['headers'] = $headers;
if (VIEWS_SEND_MIMEMAIL) {
$params['attachments'] = $attachments;
if ($plain_format) {
$params['plain'] = TRUE;
}
}
// Call Drupal standard mail function, but without sending.
$mail = \Drupal::service('plugin.manager.mail')->mail('views_send', $key, $params['to_formatted'], \Drupal::languageManager()->getDefaultLanguage()->getId(), $params, $params['from_formatted'], FALSE);
// Add additional Mime Mail post processing.
if (VIEWS_SEND_MIMEMAIL) {
// We want to spool the Subject decoded.
$mail['subject'] = Unicode::mimeHeaderDecode($mail['subject']);
}
// Updating message with data from generated mail
$message['to_mail'] = $mail['to'];
$message['from_mail'] = $mail['from'];
$message['subject'] = $mail['subject'];
$message['body'] = $mail['body'];
$message['headers'] = serialize($mail['headers']);
}
/**
* Sending a prepared message.
*
* @return
* Boolean indicating if the message was sent successfully.
*/
function views_send_deliver($message) {
if (is_array($message)) {
$message = (object) $message;
}
$key = 'direct';
$headers = unserialize($message->headers);
$mail = array(
'to' => $message->to_mail,
'from' => $message->from_mail,
'subject' => Unicode::mimeHeaderEncode($message->subject),
'body' => $message->body,
'headers' => $headers,
);
$system = $mail_backend = \Drupal::service('plugin.manager.mail')->getInstance(array('module' => 'views_send', 'key' => $key));
return $system->mail($mail);
}
/**
* Preparing and sending a message (coming from a batch job).
*/
function views_send_batch_deliver($message, $plain_format, $attachments, &$context) {
_views_send_prepare_mail($message, $plain_format, $attachments);
$status = views_send_deliver($message);
if ($status) {
if (\Drupal::config('views_send.settings')->get('debug')) {
\Drupal::logger('views_send')->notice(t('Message sent to %mail.', array('%mail' => $message['to_mail'])));
}
if (\Drupal::moduleHandler()->moduleExists('rules')) {
$event = new MailSentEvent($message);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch(MailSentEvent::EVENT_NAME, $event);
}
}
else {
$context['results'][] = t('Failed sending message to %mail - spooling it.',
array('%mail' => $message['to_mail']));
// Queue the message to the spool table.
db_insert('views_send_spool')->fields($message)->execute();
if (\Drupal::moduleHandler()->moduleExists('rules')) {
$event = new MailAddedEvent($message);
$event_dispatcher = \Drupal::service('event_dispatcher');
$event_dispatcher->dispatch(MailAddedEvent::EVENT_NAME, $event);
}
}
}
/**
* Displays status after sending messages as a batch job.
*/
function views_send_batch_deliver_finished($success, $results, $operations) {
if ($success) {
foreach ($results as $result) {
drupal_set_message($result);
}
}
}
// === Theming functions =======================================================
/**
* Theme the replacement tokens.
*
* @param $tokens:
* Keyed array with tokens as keys and description as values.
*
* @return
* A themed table with all tokens.
*
* @todo: Add help for other tokens
*/
function views_send_token_help($fields) {
$header = array(t('Token'), t('Replacement value'));
$rows = array();
foreach ($fields as $field => $title) {
$rows[] = array(VIEWS_SEND_TOKEN_PREFIX . sprintf(VIEWS_SEND_TOKEN_PATTERN, $field) . VIEWS_SEND_TOKEN_POSTFIX, $title);
}
$table = array(
'#type' => 'table',
'#header' => $header,
'#rows' => $rows
);
$output = drupal_render($table);
return $output;
}
if (\Drupal::moduleHandler()->moduleExists('token')) {
/**
* Implements hook_token_info().
*/
function views_send_token_info() {
$data = array();
$fields_name_text = _views_send_get_fields_and_tokens(NULL, 'fields_name_text');
if ($fields_name_text) {
// We are in the Views form config
foreach ($fields_name_text as $field => $title) {
$data[$field] = array(
'name' => $title,
'description' => ''
);
}
$type = array(
'name' => t('Views Send'),
'description' => t('Tokens for Views Send.'),
'needs-data' => 'views-send',
);
return array(
'types' => array('views-send' => $type),
'tokens' => array('views-send' => $data),
);
}
else {
foreach (_views_send_email_message_property_info() as $key => $info) {
$data[$key] = array(
'name' => $info['label'],
'description' => ''
);
}
$type = array(
'name' => t('Views Send e-mail message'),
'description' => t('Tokens for Views Send e-mail message.'),
'needs-data' => 'views_send_email_message',
);
return array(
'types' => array('views_send_email_message' => $type),
'tokens' => array('views_send_email_message' => $data),
);
}
}
/**
* Implementation hook_tokens().
*
* These token replacements are used by Rules and not in the Views form.
*/
function views_send_tokens($type, $tokens, array $data = array(), array $options = array()) {
$replacements = array();
if ($type == 'views_send_email_message' && !empty($data['views_send_email_message'])) {
foreach ($tokens as $name => $original) {
$replacements[$original] = $data['views_send_email_message']->{$name};
}
}
return $replacements;
}
}
/**
* Generates and returns fields and tokens.
*/
function _views_send_get_fields_and_tokens($view, $type) {
static $return;
if (isset($return[$type])) {
return $return[$type];
}
if (!in_array($type, array('fields', 'tokens', 'fields_name_text')) || !$view) {
return FALSE;
}
$fields = array();
$tokens = array();
$fields_name_text = array();
foreach ($view->field as $field_name => $field) {
// Ignore Views Send field(s).
if ($field instanceof Drupal\views_send\Plugin\views\field\ViewsSend) {
continue;
}
if (!empty($field->field)) {
$field_key = $field->field;
}
elseif (property_exists($field, 'field_alias')) {
$field_key = $field->field_alias;
if ($field_key == 'unknown') {
$field_key = $field_name;
}
}
else {
$field_key = $field_name;
}
// Add field position to ensure unique keys.
$field_key .= '_pos_' . $field->position;
$field_text = $field->label() . ' (' . $field_name . ')';
$fields[$field_key] = $field_text;
$tokens[$field_key] = $field_name;
$fields_name_text[$field_name] = $field_text;
}