-
Notifications
You must be signed in to change notification settings - Fork 1
/
cbf.module
2088 lines (1897 loc) · 63.9 KB
/
cbf.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
/*
* This hook is called at the beginning of a Drupal page request.
*/
function cbf_init() {
/*
* The City Bible Forum sites use the current Domain's machine_name
* for various purposes. Ensure that the Domain is loaded with it's
* machine name. This hacks a bug where some Domain code assumes the
* machine_name is stored globally.
*/
domain_set_domain(domain_get_domain()['domain_id']);
/*
* Implement a freeze to prevent staff adding or editing entities
*/
if (!user_is_anonymous()) {
$freeze = variable_get('cbf_content_freeze', 0);
if ($freeze) {
if (arg(0) == 'node') {
if (arg(1) == 'add' || arg(2) == 'edit') {
drupal_goto('', [], 307);
}
}
if (arg(2) == 'taxonomy') {
if (arg(4) == 'add') {
drupal_goto('', [], 307);
}
}
if (arg(0) == 'taxonomy') {
if (arg(3) == 'edit') {
drupal_goto('', [], 307);
}
}
if (arg(0) == 'eform') {
if (arg(1) == 'submit') {
drupal_goto('', [], 307);
}
}
if (arg(0) == 'entityform') {
if (arg(2) == 'edit') {
drupal_goto('', [], 307);
}
}
}
}
/*
* Variables used below.
*/
$q = $_GET['q'] ?? '';
$id = $_GET['id'] ?? '';
/*
* We have moved CiviCRM to another domain, so redirect PayPal IPN POSTs
*/
if ($q == 'civicrm/payment/ipn/13') {
watchdog('CBF', "POST /$q - " . print_r($_POST, true), [], WATCHDOG_INFO);
drupal_goto('https://civicrm.citybibleforum.org/civicrm/payment/ipn/13', [], 307);
}
/*
* Redirect people away from pages that cause SEO problems
*/
if (user_is_anonymous()) {
switch (arg(0)) {
case 'category':
drupal_goto('', [], 301);
break;
case 'taxonomy':
switch (arg(1)) {
case 'term':
drupal_goto('', [], 301);
break;
}
break;
case 'blog':
case 'blogs':
drupal_goto('articles', [], 301);
break;
}
}
/*
* Redirect people away from old forms
*/
$isOldForm = false;
switch (arg(0)) {
case 'user':
switch (arg(2)) {
case 'contact':
$isOldForm = true;
break;
}
break;
case 'contact':
case 'contact-us':
$isOldForm = true;
break;
case 'node':
switch (arg(1)) {
case '3755': // Contact Us
$isOldForm = true;
break;
}
break;
}
if ($isOldForm) {
$currentDomainId = domain_get_domain()['domain_id'];
$christianDomainId = domain_load_domain_id('christian');
if ($currentDomainId == $christianDomainId) {
drupal_goto('domain/christian/chat', [], 301);
}
else {
drupal_goto('domain/general/chat', [], 301);
}
}
if (arg(0) == 'node') {
if (arg(1) == 'add') {
/*
* This JavaScript sets some defaults when adding new nodes.
* 1. Tablefield fields default to plain text
* 2. The File Field source is ICME to encourage reuse
*/
$script = 'jQuery(document).ready(function(){
jQuery(".field-type-tablefield .filter-wrapper select.filter-list option").each(function() {
this.selected = (this.text == "Plain text");
});
jQuery(".filefield-source-imce").click();
});';
drupal_add_js($script, 'inline');
}
elseif (is_numeric(arg(1)) && arg(2) == 'edit') {
/*
* This JavaScript sets some defaults when editing nodes.
* 1. The File Field source is ICME to encourage reuse
*/
$script = 'jQuery(document).ready(function(){
jQuery(".filefield-source-imce").click();
});';
drupal_add_js($script, 'inline');
}
}
return [];
}
/*
* Implements Drupal hook_form_alter().
*
* "Perform alterations before a form is rendered"
*/
function cbf_form_alter(&$form, &$form_state, $form_id) {
$alterations = &drupal_static(__FUNCTION__, []);
/*
* Limit the views_exposed_form on the displays of the
* cbf2019_activity_components view. It should only list locations where this
* Activity is active, and there is either an Upcoming Event or a Staff member.
*/
if (
$form_id == 'views_exposed_form' &&
!empty($form_state['view']) &&
$form_state['view']->name == 'cbf2019_activity_components'
) {
$node = menu_get_object();
if (!empty($node) && $node->type == 'activity') {
if (!isset($alterations['activity'])) {
$alterations['activity'] = [];
}
if (!isset($alterations['activity']['cities'])) {
$cities = [];
// Find the Cities where there are upcoming Events
// If the event has no City, then it is visible in all cities
$current_time = strtotime('now');
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'brite_event')
->fieldCondition('field_in_activity', 'target_id', (int) $node->nid, '=')
->fieldCondition('field_next_action', 'value', $current_time, '>')
->execute();
foreach ($result as $entityType => $entityKeys) {
$entities = entity_load($entityType, array_keys($entityKeys));
foreach ($entities as $entityKey => $entity) {
$city = null;
$ministryCentres = field_get_items('node', $entity, 'taxonomy_vocabulary_1');
if ($ministryCentres === false) $ministryCentres = [];
foreach ($ministryCentres as $city) {
$i = (int) $city['tid'];
$cities[$i] = $i;
}
if ($city === null) {
$cities['All'] = 'All';
}
}
}
// Find the Cities where there are staff
// If the staff member has no City, then they are visible in all cities
$query = new EntityFieldQuery();
$result = $query
->entityCondition('entity_type', 'entityform')
->entityCondition('bundle', 'staff')
->fieldCondition('field_activities', 'target_id', (int) $node->nid, '=')
->execute();
foreach ($result as $entityType => $entityKeys) {
$entities = entity_load($entityType, array_keys($entityKeys));
foreach ($entities as $entityKey => $entity) {
$city = null;
$ministryCentres = field_get_items('entityform', $entity, 'taxonomy_vocabulary_1');
if ($ministryCentres === false) $ministryCentres = [];
foreach ($ministryCentres as $city) {
$i = (int) $city['tid'];
$cities[$i] = $i;
}
if ($city === null) {
$cities['All'] = 'All';
}
}
}
$alterations['activity']['cities'] = $cities;
}
/*
* Find the valid options for this filter
*/
if (!isset($alterations['activity']['field_highlight_location_tid'])) {
/*
* Find the possible options for this filter
*/
$exposedLocations = [];
$locations = cbf_field_get_items('node', $node, 'field_highlight_location', 'tid', []);
foreach ($locations as $location) {
$i = (int) $location;
$exposedLocations[$i] = $i;
}
/*
* The valid options for this filter are those where the corresponding
* city has an entity as calculated above. The 'All' option is valid.
* All options are valid if any of the upcoming events are not city-based.
*/
$alterations['activity']['field_highlight_location_tid'] = [];
foreach ($form['field_highlight_location_tid']['#options'] as $tid => $city) {
if (is_numeric($tid)) {
if (isset($exposedLocations[$tid])) {
if (
isset($alterations['activity']['cities']['All']) ||
isset($alterations['activity']['cities'][_cbf_convert_banner_to_city_tid($tid)])
) {
$alterations['activity']['field_highlight_location_tid'][$tid] = $city;
}
}
}
else {
$alterations['activity']['field_highlight_location_tid'][$tid] = $city;
}
}
}
/*
* There is no need to show the form if the only valid options are 'All'
* or 'All' plus one city. Otherwise, only show the valid options.
*/
if (
(
count($alterations['activity']['cities']) == 1 &&
isset($alterations['activity']['cities']['All'])
) ||
count($alterations['activity']['field_highlight_location_tid']) <= 2
) {
$form['#access'] = false;
}
else {
$form['field_highlight_location_tid']['#options']
= $alterations['activity']['field_highlight_location_tid'];
}
}
}
/*
* The domain_entityform on an -entityform-event-form is calculated when the
* form is saved. Avoid the user having to enter a value that is immediately
* overridden, by setting the #default_value to not be empty.
*/
if (stripos($form['#id'], '-entityform-edit-form') !== false) {
if (empty($form['domain_entityform']['und']['domain_id']['#default_value'])) {
$form['domain_entityform']['und']['domain_id']['#default_value'] = array(1 => 1);
}
}
/*
* If the form has a field_event_date element then validate it
*/
if (isset($form['field_event_date'])) {
$form['#validate'][] = 'cbf_field_event_date_validate';
}
/*
* If the form has a field_title_image element then validate it
*/
if (isset($form['field_title_image'])) {
$form['#validate'][] = 'cbf_field_title_image_validate';
}
/*
* If the form has a field_highlight element then validate it
*/
if (isset($form['field_highlight'])) {
$form['#validate'][] = 'cbf_field_highlight_validate';
}
/*
* If the form has a field_with element then validate it
*/
if (isset($form['field_with'])) {
$form['#validate'][] = 'cbf_field_with_validate';
}
/*
* If we are editing a node, then check whether we need to enforce creating a
* revision
*/
if (isset($form['#node_edit_form'])) {
$form['#validate'][] = 'cbf_form_revision_validate';
}
/*
* If we're editing an entity that has both a field_speakers and a field_with
* then make the field_speakers read-only
*/
$entity = $form['#node'] ?? ($form['#entity'] ?? false);
if ($entity) {
$speakers = $entity->field_speakers ?? false;
$with = $entity->field_with ?? false;
$field = $form['field_speakers'] ?? false;
if ($speakers && $with && $field) {
if ($form['field_speakers']['und']['#attributes'] ?? false) {
$form['field_speakers']['und']['#attributes']['disabled'] = true;
}
else {
$form['field_speakers']['und']['#attributes'] = ['disabled' => true];
}
}
}
}
/*
* This hook is called to alter Drupal comment forms.
*
* This change prevents anonymous users accessing the 'homepage' field.
* Spammers were using this field to get backlinks to their content on
* this website.
*/
function cbf_form_comment_form_alter(&$form, &$form_state, $form_id) {
if (user_is_anonymous()) {
if (isset($form['author']['homepage']['#access'])) {
$form['author']['homepage']['#access'] = false;
}
}
}
/*
* Validate field_event_date elements on forms.
* - an event can't last longer than 5 days. This prevents staff misusing
* Events when they should be using a News Story.
*/
function cbf_field_event_date_validate($form, &$form_state) {
if (isset($form_state['values']['field_event_date'])) {
$duration = 0;
$occurrences = 0;
foreach (reset($form_state['values']['field_event_date']) as $event_occurrence) {
if (is_array($event_occurrence)) {
$start_time = new DateObject($event_occurrence['value'], $event_occurrence['timezone']);
$startstamp = strtotime($start_time->format('Y-m-d H:i:s O'));
$end_time = new DateObject($event_occurrence['value2'], $event_occurrence['timezone']);
$endstamp = strtotime($end_time->format('Y-m-d H:i:s O'));
$duration += $endstamp - $startstamp;
$occurrences++;
}
}
if ($duration > 5 * 24 * 60 * 60) {
form_set_error(
'field_event_date',
'The overall duration of this event is greater than 5 days. ' .
'This doesn\'t seem like an event.');
}
if ($occurrences > 1) {
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'taxonomy_term')
->entityCondition('bundle', 'event_registration_type');
$result = $query->execute();
foreach ($result as $entityType => $entities) {
$terms = taxonomy_term_load_multiple(array_keys($entities));
foreach ($terms as $term) {
if (stripos($term->name, 'EventBrite') !== false) {
$buttons = $form_state['values']['field_registration_buttons'] ?? [[]];
foreach (reset($buttons) as $button) {
$tid = reset($button['field_event_registration_type']);
$tid = $tid ? reset($tid) : $tid;
$tid = $tid ? reset($tid) : $tid;
if ($tid == $term->tid) {
form_set_error(
'field_event_date',
'Cannot mix repeating dates with EventBrite registration');
break 3;
}
}
}
}
}
}
}
}
/*
* Validate field_title_image elements on forms.
* - Title images are mandatory for non-Unlisted activities
*/
function cbf_field_title_image_validate($form, &$form_state) {
if (isset($form_state['node'])
&& $form_state['node']->type == 'activity') {
$unlisted = '1957';
$fid = $form_state['values']['field_title_image'];
$fid = is_array($fid) ? reset($fid) : '0';
$fid = is_array($fid) ? reset($fid)['fid'] ?? '0' : '0';
$audience = $form_state['values']['taxonomy_vocabulary_3'];
$audience = is_array($audience) ? reset($audience) : '0';
$audience = is_array($audience) ? reset($audience)['tid'] ?? '0' : '0';
if ($audience != $unlisted && $fid == '0') {
form_set_error(
'field_highlight',
'The Title image must be supplied unless the Activity is Unlisted.');
}
}
}
/*
* Validate field_highlight elements on forms.
* - Highlight images are mandatory for non-Unlisted episodes & blogs
* - only apply this rule to modern articles
* Highlight images are required for brite_events so no special processing is
* required for those.
*/
function cbf_field_highlight_validate($form, &$form_state) {
if (
(isset($form_state['node'])
&& ($form_state['node']->type == 'episode'
|| $form_state['node']->type == 'blog')
&& (!isset($form_state['node']->nid)
|| $form_state['node']->nid > 5898))
) {
$unlisted = '1957';
$fid = $form_state['values']['field_highlight'];
$fid = is_array($fid) ? reset($fid) : '0';
$fid = is_array($fid) ? reset($fid)['fid'] ?? '0' : '0';
$audience = $form_state['values']['taxonomy_vocabulary_3'];
$audience = is_array($audience) ? reset($audience) : '0';
$audience = is_array($audience) ? reset($audience)['tid'] ?? '0' : '0';
if ($audience != $unlisted && $fid == '0') {
form_set_error(
'field_highlight',
'The Highlight image must be supplied unless the article is Unlisted.');
}
}
}
/*
* Validate field_with elements on forms.
* - Check that the nominated Person has an existing Speaker record which
* has both a bio/description and an image
* - If this is a new person then require both a bio/description and an image
* - Warn if the bio/description of the existing Speaker record is longer than
* 500 characters
* - Warn if the bio/description is longer than 500 characters
*/
function cbf_field_with_validate($form, &$form_state) {
if (is_array($form_state['values']['field_with'])) {
$people = reset($form_state['values']['field_with']);
}
else {
$people = [];
}
$maxDescription = 500;
foreach ($people as $key => $person) {
if (is_numeric($key)) { // Ignore people who are in the process of being added
$tid = $person['field_speaker'];
$tid = is_array($tid) ? reset($tid) : 0;
$name = is_array($tid) ? reset($tid)['name'] ?? '' : '';
$tid = is_array($tid) ? reset($tid)['tid'] ?? 0 : 0;
if (is_numeric($tid)) { // Existing speaker
if ($tid > 0) {
$speaker = taxonomy_term_load($tid);
if (!$person['field_description']['und'][0]['value']) {
if ($speaker->description) {
if (strlen($speaker->description) > $maxDescription) {
drupal_set_message(
"The existing Speaker record for '{$speaker->name}' has a description that is longer than $maxDescription characters (it will overflow the display area)",
'warning');
}
}
else {
form_set_error(
"field_with][und][$key][field_description][und][0][value",
"The existing Speaker record for '{$speaker->name}' doesn't have a description. Need to add one here or on the Speaker record.");
}
}
if (!$person['field_highlight']['und'][0]['fid'] && !$speaker->field_highlight
&& !$person['field_image']['und'][0]['fid'] && !$speaker->field_image) {
form_set_error(
"field_with][und][$key][field_highlight][und][0][value",
"The existing Speaker record for '{$speaker->name}' doesn't have an image. Need to add one here or on the Speaker record.");
}
}
}
else { // New speaker
if (!$person['field_description']['und'][0]['value']) {
form_set_error(
"field_with][und][$key][field_description][und][0][value",
"'$name' needs a description as there is no existing Speaker record");
}
if (!$person['field_highlight']['und'][0]['fid']
&& !$person['field_image']['und'][0]['fid']) {
form_set_error(
"field_with][und][$key][field_highlight][und][0][value",
"'$name' needs an image as there is no existing Speaker record");
}
}
$description = $person['field_description']['und'][0]['value'] ?? '';
if (strlen($description) > $maxDescription) {
drupal_set_message(
"The description supplied for '$name' is longer than $maxDescription characters (it will overflow the display area)",
'warning');
}
}
}
}
/*
* If we are editing a node, then check whether we need to enforce creating a
* revision.
*
* Note that cbf_form_alter() attaches cbf_form_revision_validate() to the form
* when $form['#node_edit_form'] is set.
*/
function cbf_form_revision_validate($form, &$form_state) {
/*
* The node lifecycle is assumed to be ...
*
* - development - during the first month the node is rapidly developed, so
* creating revisions is not needed
* - use - during the next 5 months there are occasional changes,
* and only certain changes require a revision
* - reuse - thereafter changes require a revision so we can preserve
* the original content
*/
$developmentMilestone = strtotime('1 month ago');
$reuseMilestone = strtotime('1 year ago');
/*
* When was the node created?
*/
if (isset($form_state['node']->nid)) {
$created = $form_state['node']->created;
}
else {
$created = time();
}
/*
* Are there any reasons to enforce a revision?
*/
$reason = [];
$revision = $form_state['input']['revision'] ?? false;
$log = $form_state['input']['log'] ?? '';
global $user;
if ($user->uid == 1) {
// The super-user doesn't need to make revisions
}
else if ($revision && $log) {
// There is already a valid revision
}
else if ($created < $reuseMilestone) {
$reason[] = 'This node is more than 1 year old so the original content should be preserved';
}
else if ($created < $developmentMilestone) {
/*
* After development there are some cases when a revision is required
*/
if ($form_state['node']->type == 'activity') {
$reason[] = 'This node is an Activity';
}
foreach ($form_state['input'] as $input) {
if (is_array($input)) {
$input = reset($input);
if (is_array($input)) {
$input = reset($input);
$input = $input['format'] ?? '';
if (strpos($input, 'shortcodes') !== false) {
$reason[] = 'This node uses Dynamic Shortcodes';
break;
}
}
}
}
}
$warning = false;
if (!empty($reason)) {
if ($warning) {
drupal_set_message(
'Soon you will be required to create a revision since: '
. implode(', ', $reason)
. '. The revision will be required to have a log message.',
'warning');
}
else {
form_set_error('revision', 'Need to create a revision: ' . implode(', ', $reason));
form_set_error('log', 'Need a revision log message: see the <em>Revision information</em> tab just above the <em>Save</em> button at the bottom of the screen');
}
}
}
/*
* Implement the rules that assign entities to domains.
*
* Rules are stored in the domain information ...
*
* machine_name = christian
* alias = christian.audience.rule |
* all.audience.rule
*
* Always matches.
*
* machine_name = general
* alias = general.audience.rule
*
* Matches content for a General audience.
*
* The rules have the following effects on nodes...
*
* domain_site false (content is not available in all affiliates)
* domains contains an entry for each domain that matches a rule
* domain_source DOMAIN_SOURCE_USE_ACTIVE (don't change domain to a cardinal
* domain) EXCEPT when the node appears in only one domain
*/
function cbf_entity_presave($entity, $type) {
switch ($type) {
case 'node':
$url0 = 'node';
$allDomainBundles = [
'contact_webform' => true,
'webform' => true,
'office' => true,
];
$skipDomainBundles = [ ];
$allDomainIds = [
61 => 'Privacy policy',
];
$entityId = $entity->nid;
$entityBundle = $entity->type;
break;
case 'entityform':
$url0 = 'entityform';
$allDomainBundles = [
'staff' => true,
'home_page_slider' => true,
];
$skipDomainBundles = [
'title_header' => true,
];
$allDomainIds = [ ];
$entityId = $entity->entityform_id;
$entityBundle = $entity->type;
break;
default:
return;
}
/*
* If saving an entity after editing it, clear the views data cache so the
* staff member editing the node can see the refreshed version of the views
* blocks on the page.
*/
if (arg(0) == $url0 && arg(2) == 'edit') {
cache_clear_all('*', 'cache_views_data', true);
}
$followDomainRules = empty($skipDomainBundles[$entityBundle]);
if ($followDomainRules) {
$domains = domain_list_by_machine_name();
$matches = [];
$audienceTerm = cbf_field_get_items($type, $entity, 'taxonomy_vocabulary_3', 'tid', '');
switch ($audienceTerm) {
case '47':
$entityAudience = 'christian';
break;
case '48':
$entityAudience = 'general';
break;
case '1957':
$entityAudience = 'unlisted';
break;
default:
$entityAudience = '';
break;
}
foreach ($domains as $domain) {
$match = false;
if (isset($allDomainBundles[$entityBundle])) {
$match = true;
}
else if (isset($allDomainIds[$entityId])) {
$match = true;
}
else {
$ruleAudience = $domain['machine_name'];
if (
$ruleAudience == 'christian' ||
$ruleAudience == 'general' && (
$entityAudience == 'general' ||
$entityAudience == 'unlisted'
)
) {
$match = true;
}
}
if ($match) {
$matches[$domain['machine_name']] = [ 'domain_id' => $domain['domain_id'] ];
}
}
switch ($type) {
case 'node':
$entity->domain_site = false;
$entity->domains = [ ];
foreach ($matches as $domain) {
$entity->domains[$domain['domain_id']] = $domain['domain_id'];
}
if (count($entity->domains) == 1) {
$entity->domain_source = reset($entity->domains);
}
else if ($entityAudience == 'unlisted') {
$entity->domain_source = DOMAIN_SOURCE_USE_ACTIVE;
}
else {
$sources = [ ];
foreach ($matches as $name => $domainId) {
switch ($name) {
case 'general':
case 'christian':
$sources[$name] = $domainId['domain_id'];
break;
default:
$sources['other'] = DOMAIN_SOURCE_USE_ACTIVE;
break;
}
}
/*
* The domain source is DOMAIN_SOURCE_USE_ACTIVE for Bigger
* Questions etc, the 'general' domain for content visible on
* the general and christian domains, the 'christian' domain
* for content visible on the Christian domain, and
* DOMAIN_SOURCE_USE_ACTIVE as a final fallback.
*/
$entity->domain_source = $sources['other']
?? $sources['general']
?? $sources['christian']
?? DOMAIN_SOURCE_USE_ACTIVE;
}
break;
case 'entityform':
$lang = field_language($type, $entity, 'domain_entityform');
$entity->domain_entityform[$lang] = [ ];
foreach ($matches as $value) {
$entity->domain_entityform[$lang][] = $value;
}
break;
}
}
/*
* When saving an entity with field_with items, update field_speakers to
* match. Update the description and images in the $speaker term if not
* yet set.
*/
if ($entity->field_with['und'] ?? false) {
$personnel = cbf_field_get_items($type, $entity, 'field_with', 'value', []);
$personnel = entity_load('paragraphs_item', $personnel);
$first = true;
foreach ($personnel as $person) {
$tid = cbf_field_get_items('paragraphs_item', $person, 'field_speaker', 'tid');
// Update the field_speakers
if (isset($entity->field_speakers)) {
if ($first) {
$entity->field_speakers = ['und' => []];
}
$entity->field_speakers['und'][] = ['tid' => $tid,];
}
// Update the $speaker term if needed
$speaker = taxonomy_term_load($tid);
$changed = false;
$description = cbf_field_get_items('paragraphs_item', $person, 'field_description', 'value');
if ($description && !$speaker->description) {
$speaker->description = $description;
$changed = true;
}
if ($person->field_highlight && !$speaker->field_highlight) {
$speaker->field_highlight = $person->field_highlight;
$changed = true;
}
if ($person->field_image && !$speaker->field_image) {
$speaker->field_image = $person->field_image;
$changed = true;
}
if ($changed) {
taxonomy_term_save($speaker);
}
$first = false;
}
}
}
/*
* CKEditor introduces some unpleasant artifacts into HTML text fields. This
* function handles them ...
*
* - Empty paragraphs are removed
* - Non-breaking spaces are replaced with plain spaces
* - Ensure target="_blank" attributes have a rel="noopener noreferrer"
* attribute https://medium.com/@jitbit/target-blank-the-most-underestimated-vulnerability-ever-96e328301f4c#.dzwczm21q
*
* The order of these actions is important as the patterns have overlapping content.
*/
function cbf_field_attach_presave($entity_type, $entity) {
if ($entity_type == 'node') {
$html_fields = array('body', 'field_short_form', 'field_sidebar_content');
$attributes = array('summary','value');
$replacements = array(
'!<p>(\r\n\t)* </p>!i' => '',
'! !i' => ' ',
'!target="_blank" rel="noopener noreferrer"!i' => 'target="_blank"',
'!target="_blank"!i' => 'rel="noopener noreferrer" target="_blank"',
'!rel="noopener noreferrer" rel="noopener noreferrer"!i' => 'rel="noopener noreferrer"',
);
$from = array_keys($replacements);
$to = array_values($replacements);
foreach ($html_fields as $html_field) {
if (isset($entity->$html_field)) {
$field = & $entity->$html_field;
$languages = array_keys($field);
foreach ($languages as $language) {
$instances = count($field[$language]);
for ($instance = 0; $instance < $instances; $instance++) {
foreach ($attributes as $attribute) {
if (isset($field[$language][$instance][$attribute])) {
$field[$language][$instance][$attribute]
= preg_replace($from, $to, $field[$language][$instance][$attribute]);
}
}
}
}
}
}
}
}
/*
* This function is called by Drupal cron.
*
* Re-save entities that have a field_next_action which is set to a time between
* the previous invocation of cron and this one. This enacts time-sensitive
* calculations of computed field values.
*
* Prevent nodes that were posted to Twitter from being automatically re-posted if
* they are edited.
*
* The time that cron was run is updated for next time.
*/
function cbf_cron() {
$current_time = strtotime('now');
/*
* Run this cron function as the super-user to avoid access restrictions
* with Domain Entity.
*
* Following the pattern in https://www.drupal.org/node/1793862
*/
global $user;
try {
// Switch to the super-user
$originalUser = $user;
$originalState = drupal_save_session(false);
$user = user_load(1);
/*
* Find entities with field_next_action due. Order them so the most recent
* are processed first, so entities that get stuck don't mask later ones.
*/
$query = new EntityFieldQuery();
$result = $query
->fieldCondition('field_next_action', 'value', [1, $current_time], 'BETWEEN')
->fieldOrderBy('field_next_action', 'value', 'DESC')
->range(0, 50)
->execute();
foreach ($result as $entityType => $entityKeys) {
$entities = entity_load($entityType, array_keys($entityKeys));
foreach ($entities as $entityKey => $entity) {
switch ($entityType) {
case 'node':
node_save($entity);
break;
}
unset($entityKeys[$entityKey]);
}
if (!empty($entityKeys)) {
watchdog(
'CBF',
"Couldn't process $entityType entities with a field_next_action set: ". implode(', ',array_keys($entityKeys)),
null,
WATCHDOG_ERROR
);
}
}
} catch (Exception $e) {
// Do nothing
}
// Switch back to the original user
$user = $originalUser;
drupal_save_session($originalState);
variable_set('cbf_cron_last_run', $current_time);
}
/*
* When a comment is made in reply to a comment, and email is sent
* to the author of the original comment. If there is no original
* comment, the comment is being made directly on the article, but
* Drupal still attempts to send an email. The "To" header will in
* this case be an unresolved token and will fail to be delivered.
* Don't send emails in this case.
*
* The Contact module sends emails using the To: address supplied
* by the visitor to a citybibleforum.org address. When this is
* redirected to a gmail.com address Gmail rightly complains
* (Unauthenticated email from yahoo.com is not accepted due to
* domain's 550-5.7.1 DMARC policy)
*
* Change the message headers so the email is sent From the Sender