-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnexteuropa_varnish.module
967 lines (854 loc) · 29.4 KB
/
nexteuropa_varnish.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
<?php
/**
* @file
* Module file.
*/
module_load_include('inc', 'nexteuropa_varnish', 'nexteuropa_varnish.helper');
use Drupal\nexteuropa_varnish\PurgeRuleType;
define('NEXTEUROPA_VARNISH_CACHE_TABLE', 'cache_nexteuropa_varnish');
/**
* Implements hook_menu().
*/
function nexteuropa_varnish_menu() {
$items['admin/config/system/nexteuropa-varnish'] = array(
'title' => 'Next Europa Varnish - Configuration',
'description' => 'Configuration of the Varnish cache invalidation mechanism.',
'page callback' => 'drupal_get_form',
'page arguments' => array('nexteuropa_varnish_admin_settings_form'),
'access arguments' => array('administer frontend cache purge rules'),
'file' => 'nexteuropa_varnish.admin.inc',
);
$items['admin/config/system/nexteuropa-varnish/purge/%'] = array(
'title' => 'Next Europa Varnish - Purge confirmation',
'description' => 'Confirmation form for Drupal and Varnish purge.',
'page callback' => 'drupal_get_form',
'page arguments' => array('nexteuropa_varnish_purge_all_form', 5),
'access callback' => '_nexteuropa_varnish_purge_all_access',
'file' => 'nexteuropa_varnish.admin.inc',
'type' => MENU_CALLBACK,
);
$items['admin/config/system/nexteuropa-varnish/general'] = array(
'title' => 'General settings',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
return $items;
}
/**
* Implements hook_entity_info().
*/
function nexteuropa_varnish_entity_info() {
return array(
'nexteuropa_varnish_cache_purge_rule' => array(
'module' => 'nexteuropa_varnish',
'label' => t('Cache purge rule'),
'fieldable' => FALSE,
'entity keys' => array(
'id' => 'id',
),
'label callback' => 'nexteuropa_varnish_cache_purge_rule_label',
'base table' => 'nexteuropa_varnish_cache_purge_rule',
'entity class' => 'Drupal\\nexteuropa_varnish\\Entity\\PurgeRule',
'controller class' => 'Drupal\\nexteuropa_varnish\\PurgeRuleController',
'access callback' => 'nexteuropa_varnish_cache_purge_rule_access',
'admin ui' => array(
'path' => 'admin/config/system/nexteuropa-varnish/purge_rules',
'controller class' => 'NexteuropaVarnishCachePurgeRuleEntityUIController',
'file' => 'nexteuropa_varnish.rules.admin.inc',
),
),
);
}
/**
* Implements hook_flush_caches().
*/
function nexteuropa_varnish_flush_caches() {
return array(NEXTEUROPA_VARNISH_CACHE_TABLE);
}
/**
* Implements hook_permission().
*/
function nexteuropa_varnish_permission() {
return array(
'administer frontend cache purge rules' => array(
'title' => 'Administer frontend cache purge rules',
'description' => '',
'restrict access' => TRUE,
),
);
}
/**
* Access callback for the cache purge rule entity..
*
* @param string $op
* The operation being performed. One of 'view', 'update', 'create', 'delete'
* or just 'edit' (being the same as 'create' or 'update').
* @param object $cache_purge_rule
* (optional) A cache purge rule to check access for. If nothing is given,
* access for all cache purge rules is determined.
* @param object $account
* (optional) The user to check for. Leave it to NULL to check for the
* global user.
*
* @return bool
* Whether access is allowed or not.
*/
function nexteuropa_varnish_cache_purge_rule_access($op, $cache_purge_rule = NULL, $account = NULL) {
return user_access('administer frontend cache purge rules', $account);
}
/**
* Label callback for the cache purge rule entity.
*
* @param object $purge_rule
* The cache purge rule.
*/
function nexteuropa_varnish_cache_purge_rule_label($purge_rule) {
if (isset($purge_rule->id)) {
return t('cache purge rule !id', array('!id' => $purge_rule->id));
}
return t('new cache purge rule');
}
/**
* Implements hook_workbench_moderation_transition().
*/
function nexteuropa_varnish_workbench_moderation_transition($node, $previous_state, $new_state) {
if (_nexteuropa_varnish_prevent_purge()) {
return;
}
// No rule defined for the node: Ignore the rest of the process.
if (!nexteuropa_varnish_node_has_rules($node)) {
return;
}
// Paths of the previous node revision are retrieved to control if they have
// changed.
// If it is the case and the node is already published, that means some
// node URLs are not valid anymore, and their references in the Varnish index
// must be purged.
$updated_node_paths = array();
if (empty($node->is_new) && (isset($node->workbench_moderation['published']))) {
$updated_node_paths = _nexteuropa_varnish_get_updated_node_paths($node);
}
// Something must be sent to Varnish when a new content
// revision is published.
$publishing = ($new_state == workbench_moderation_state_published());
// Something must be sent to Varnish when the content
// is unpublished (no published revision anymore).
$unpublishing = !$publishing &&
($node->workbench_moderation['my_revision']->published == 1)&&
($node->status == NODE_NOT_PUBLISHED);
if ($publishing || $unpublishing || !empty($updated_node_paths)) {
_nexteuropa_varnish_process_paths_sending($node, $updated_node_paths);
}
}
/**
* Implements hook_node_insert().
*/
function nexteuropa_varnish_node_insert($node) {
if ($node->status == NODE_PUBLISHED) {
nexteuropa_varnish_node_update($node);
}
}
/**
* Implements hook_node_update().
*/
function nexteuropa_varnish_node_update($node) {
// Ignore moderated nodes, they are handled by the workbench moderation hooks
// implemented in this module.
if (workbench_moderation_node_moderated($node)) {
return;
}
if (_nexteuropa_varnish_prevent_purge()) {
return;
}
// No rule defined for the node: Ignore the rest of the process.
if (!nexteuropa_varnish_node_has_rules($node)) {
return;
}
// Ignore updates on existing, unpublished content that remains unpublished.
if (($node->status == NODE_NOT_PUBLISHED) &&
(isset($node->original) && ($node->original->status == NODE_NOT_PUBLISHED))
) {
return;
}
// Paths of the previous node revision are retrieved to control if they have
// changed.
// If it is the case and the node is already published, that means some
// node URLs are not valid anymore, and their references in the Varnish index
// must be purged.
$updated_node_paths = _nexteuropa_varnish_get_updated_node_paths($node);
_nexteuropa_varnish_process_paths_sending($node, $updated_node_paths);
}
/**
* Implements hook_node_presave().
*
* It adds the old node paths (I.E. aliases) in the node object in order to
* make further control later in the node saving process.
*
* @see nexteuropa_varnish_workbench_moderation_transition()
* @see nexteuropa_varnish_node_update()
*/
function nexteuropa_varnish_node_presave($node) {
$node->nexteuropa_varnish_old_paths = array();
// Even if the node has just been created it will receive an "old" path that
// corresponds to the creation form path.
// With this, old_paths must be set with values.
if (empty($node->is_new)) {
$node->nexteuropa_varnish_old_paths = _nexteuropa_varnish_get_node_paths($node);
}
}
/**
* Implements hook_node_delete().
*/
function nexteuropa_varnish_node_delete($node) {
// No rule defined for the node: Ignore the rest of the process.
if (!nexteuropa_varnish_node_has_rules($node)) {
return;
}
$paths = array();
$entity_uri = entity_uri('node', $node);
if (NULL !== $entity_uri) {
$url_locale = language_negotiation_get('language', 'locale-url');
$url_suffix = language_negotiation_get('language', 'nexteuropa_multilingual_url_suffix');
// Add logic to send a language prefix/suffix regex for non aliased paths.
$lgregex = '';
if ($url_locale) {
$lgregex = '[a-z]{2}\/';
}
elseif ($url_suffix) {
$lgregex = '_[a-z]{2}';
}
$original_path = $entity_uri['path'];
$alias = drupal_get_path_alias($original_path);
// Get the node\/nid.
$paths['unaliased'] = preg_quote($original_path, '/');
// Add regex prefix or suffix if needed.
// Example node\/nid_[a-z]{2}.
$paths['full_unaliased'] = $url_suffix ? $paths['unaliased'] . $lgregex : $lgregex . $paths['unaliased'];
// Add escaped alias.
// Example content\/my\-page.
$paths['escaped_alias'] = preg_quote($alias, '/');
// Add regex prefix or suffix if needed to alias.
// Example content\/my\-page_[a-z]{2}.
$paths['alias_prefix'] = $url_suffix ? $paths['escaped_alias'] . $lgregex : $lgregex . $paths['escaped_alias'];
}
// Add custom purge rules.
$purge_rules = nexteuropa_varnish_get_node_purge_rules($node);
foreach ($purge_rules as $purge_rule) {
if ($purge_rule->type() == PurgeRuleType::PATHS) {
$paths = array_merge($paths, $purge_rule->paths());
}
}
if (!empty($paths)) {
$paths = array_unique($paths);
$paths = array_filter($paths);
_nexteuropa_varnish_purge_paths($paths);
}
}
/**
* Implements hook_file_delete().
*/
function nexteuropa_varnish_file_delete($file) {
_nexteuropa_varnish_flush_file($file);
}
/**
* Implements hook_file_update().
*/
function nexteuropa_varnish_file_update($file) {
_nexteuropa_varnish_flush_file($file);
}
/**
* Implements hook_path_delete().
*/
function nexteuropa_varnish_path_delete($path) {
if (empty($path)) {
return;
}
$node = menu_get_object('node', 1, $path['source']);
$is_file = strpos($path['source'], 'file/');
// Has to be a node or file path.
if ($node === NULL && $is_file === FALSE) {
return;
}
// No rule defined for the node: Ignore the rest of the process.
if ($node !== NULL && nexteuropa_varnish_node_has_rules($node) === FALSE) {
return;
}
$url_locale = language_negotiation_get('language', 'locale-url');
$url_suffix = language_negotiation_get('language', 'nexteuropa_multilingual_url_suffix');
// Add logic to send a language prefix/suffix regex for non aliased paths.
$lgregex = '';
if ($url_locale) {
$lgregex = '[a-z]{2}\/';
}
elseif ($url_suffix) {
$lgregex = '_[a-z]{2}';
}
// Escaped alias.
// Example content\/my\-page.
$escaped_alias = preg_quote($path['alias'], '/');
// Add regex prefix or suffix if needed.
$paths['alias_prefix'] = $url_suffix ? $escaped_alias . $lgregex : $lgregex . $escaped_alias;
$paths['alias'] = $escaped_alias;
if (!empty($paths)) {
$paths = array_unique($paths);
$paths = array_filter($paths);
_nexteuropa_varnish_purge_paths($paths);
}
}
/**
* Gets purge rules to apply for a specific node.
*
* @param object $node
* The node for which the rules are to be retrieved.
*
* @return array|bool
* An array of nexteuropa_varnish_cache_purge_rule objects indexed by their
* ids. When no results are found, an empty array is returned.
*/
function _nexteuropa_varnish_get_paths_to_purge($node) {
$paths = array();
$exist_node_path_rule = FALSE;
$purge_rules = nexteuropa_varnish_get_node_purge_rules($node);
foreach ($purge_rules as $purge_rule) {
if ($purge_rule->type() == PurgeRuleType::PATHS) {
$paths = array_merge($paths, $purge_rule->paths());
}
else {
$exist_node_path_rule = TRUE;
}
}
$is_default_rule = variable_get('nexteuropa_varnish_default_purge_rule', FALSE);
if (($exist_node_path_rule || $is_default_rule)) {
$node_paths = _nexteuropa_varnish_get_node_paths($node);
$paths = array_merge($paths, $node_paths);
}
// NEPT-1163: Removing base path from the collected paths.
$paths = array_map('_nexteuropa_varnish_trim_base_path', $paths);
return $paths;
}
/**
* Get the paths to purge for a specific node.
*
* @param object $node
* The node.
*
* @return string[]
* The paths to purge for this node.
*/
function nexteuropa_varnish_get_node_purge_rules($node) {
$cache_id = __FUNCTION__ . '_' . $node->type;
$rules = &drupal_static($cache_id, array());
if (!empty($rules)) {
return $rules;
}
if ($cache = cache_get($cache_id, NEXTEUROPA_VARNISH_CACHE_TABLE)) {
$rules = $cache->data;
return $rules;
}
$type = $node->type;
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'nexteuropa_varnish_cache_purge_rule')
->addTag('allow_all_entity')
->addMetaData('type', $type);
$result = $query->execute();
if (isset($result['nexteuropa_varnish_cache_purge_rule'])) {
$rules = entity_load(
'nexteuropa_varnish_cache_purge_rule',
array_keys($result['nexteuropa_varnish_cache_purge_rule'])
);
cache_set($cache_id, $rules, NEXTEUROPA_VARNISH_CACHE_TABLE, CACHE_TEMPORARY);
}
return $rules;
}
/**
* Implements hook_query_TAG_alter().
*
* Alters the query for finding rules applying to all.
*/
function nexteuropa_varnish_query_allow_all_entity_alter(QueryAlterableInterface $query) {
$type = $query->getMetaData('type');
$or = db_or()->condition('content_type', 'all')->condition('content_type', $type);
$query->condition($or);
}
/**
* Purges certain paths on the web frontend cache.
*/
function _nexteuropa_varnish_purge_paths($paths, $varnish_rules_uri = 'admin/config/system/nexteuropa-varnish/purge_rules') {
// First clear the actual backend page cache (usually DrupalDatabaseCache).
// Otherwise the web frontend cache will receive again
// outdated cached versions of pages.
// Be aware that this clears the full page cache instead of clearing only
// certain pages. To make it more precise, we need to have full knowledge of
// all possible base URLs. This can be improved later on.
cache_clear_all('*', 'cache_page', TRUE);
// Escape the paths for usage in a regular expression.
$escaped_paths = array_map(
function ($regex) use ($varnish_rules_uri) {
// Check if the regular expression is valid.
if (@preg_match('/' . $regex . '/', NULL) !== FALSE) {
return $regex;
}
else {
drupal_set_message(
t(
'Please !check_config, the regex %regex you are trying to flush is not valid. We suggest you review and save your regex rules again using <a href="@doc">the documentation available</a>. In case of doubt, please contact your site administrator or the devops team.',
array(
'!check_config' => l(
t('check your varnish rules'),
$varnish_rules_uri),
'%regex' => $regex,
'@doc' => "https://github.com/ec-europa/digit-ne-varnish#purge-nodes-that-match-this-regex",
)
),
'error');
}
},
$paths
);
if ((int) variable_get('nexteuropa_varnish-granularity', 2) === 2) {
watchdog(
'nexteuropa_varnish',
'Clearing paths: @paths',
array(
'@paths' => implode(', ', $escaped_paths),
),
WATCHDOG_INFO
);
}
_nexteuropa_varnish_varnish_requests_send($escaped_paths);
}
/**
* Sends the purge HTTP requests to the different Varnish servers.
*
* The servers that must receive purging request are defined in the module's
* settings.
*
* @param array $path_regexp_rules
* The purge URL purge rule(s) (X-Invalidate-Regexp) sent to Varnish.
* Rules must contain escaped paths.
*
* @return bool
* TRUE if all requests have been sent successfully; otherwise FALSE.
*/
function _nexteuropa_varnish_varnish_requests_send($path_regexp_rules = array()) {
if (_nexteuropa_varnish_prevent_purge()) {
return FALSE;
}
try {
$settings = _nexteuropa_varnish_get_varnish_settings();
$request_options = _nexteuropa_varnish_prepare_request_options($path_regexp_rules, $settings);
// Sending the HTTP requests to the Varnish server(s)
$http_targets = $settings['varnish_http_targets'];
$request_path = '/invalidate';
$requests_ok = TRUE;
foreach ($http_targets as $target) {
$url = sprintf('%s%s', $target, $request_path);
$response = drupal_http_request(
$url,
$request_options
);
if (isset($response->error) && (int) variable_get('nexteuropa_varnish-granularity', 2) > 0) {
watchdog(
'nexteuropa_varnish',
'Clear operation failed for target %target: %code %error',
array(
'%target' => $target,
'%error' => $response->error,
'%code' => $response->code,
),
WATCHDOG_ERROR
);
$requests_ok = FALSE;
}
}
return $requests_ok;
}
catch (InvalidArgumentException $iae) {
if ((int) variable_get('nexteuropa_varnish-granularity', 2) > 0) {
$log_link = l(t('status report page'), 'admin/reports/status_en');
watchdog(
'nexteuropa_varnish',
'No path has been sent for clearing because all module settings are not set.',
array(),
WATCHDOG_CRITICAL,
$log_link
);
}
return FALSE;
}
}
/**
* Prepares Options use of the HTTP requests sent to the Varnish servers.
*
* @param array $path_regexp_rules
* The purge URL purge rule(s) (X-Invalidate-Regexp) sent to Varnish.
* Rules must contain escaped paths.
* @param array $settings
* The authentication attributes to inject in the request header; I.E.:
* - varnish_request_user: the Varnish authentication user;
* - varnish_request_password:the Varnish authentication password;
* - varnish_tag: Site's Varnish tag;
* - varnish_request_method: The HTTP method to use with the request;
* - varnish_http_timeout: The timeout to set for the request.
* If empty, the values set in the module configuration are used.
*
* @return array
* The HTTP request options have the following elements:
* - headers: An array containing request headers with the Varnish
* "X-Invalidate" parameters.
* - method: A string containing the request method as define in the module
* configuration.
* - timeout: A float representing the request time out expressed in seconds,
* as define in the module configuration.
*
* @throws \InvalidArgumentException
* If the settings are incomplete.
*
* @see drupal_http_request()
*/
function _nexteuropa_varnish_prepare_request_options($path_regexp_rules = array(), $settings = array()) {
if (!$settings) {
$settings = _nexteuropa_varnish_get_varnish_settings();
}
$additional_headers = array();
// Preparing the requests for Varnish server(s).
$base_request_headers = _nexteuropa_varnish_base_request_headers($settings);
// Prepare values for 'X-Invalidate-Type' and 'X-Invalidate-Regexp' on the
// basis of $path_regexp_rules.
if (!empty($path_regexp_rules)) {
$invalidate_type = 'regexp';
$sent_regexp = "^(" . implode('|', $path_regexp_rules) . ")$";
$additional_headers = array(
'X-Invalidate-Regexp' => $sent_regexp,
);
}
else {
$invalidate_type = 'full';
};
$request_headers = $base_request_headers + $additional_headers + array(
'X-Invalidate-Tag' => $settings['varnish_tag'],
'X-Invalidate-Type' => $invalidate_type,
);
$request_method = $settings['varnish_request_method'];
return array(
'headers' => $request_headers,
'method' => $request_method,
'timeout' => $settings['varnish_http_timeout'],
);
}
/**
* Get the base headers for the web frontend cache purge requests.
*
* @param array $settings
* The authentication attributes to inject in the request header; I.E.:
* - varnish_request_user: the Varnish authentication user;
* - varnish_request_password:the Varnish authentication password;
* If empty, the values set in the module configuration are used.
*
* @return array
* Key value pairs of request headers.
*
* @throws \InvalidArgumentException
* If the settings are incomplete.
*/
function _nexteuropa_varnish_base_request_headers($settings = array()) {
$headers = array();
if (!$settings) {
$settings = _nexteuropa_varnish_get_varnish_settings();
}
$request_user = $settings['varnish_request_user'];
$request_password = $settings['varnish_request_password'];
if ($request_user && $request_password) {
$basic_auth = base64_encode("{$request_user}:{$request_password}");
$headers['Authorization'] = 'Basic ' . $basic_auth;
}
return $headers;
}
/**
* Returns paths for the node including translations.
*
* @param object $node
* Node object.
*
* @return array
* An array with the paths of the node.
*/
function _nexteuropa_varnish_get_node_paths($node) {
$paths = array();
$original_alias = '';
$entity_uri = entity_uri('node', $node);
if (NULL !== $entity_uri) {
$url_locale = language_negotiation_get('language', 'locale-url');
$url_suffix = language_negotiation_get('language', 'nexteuropa_multilingual_url_suffix');
// Add logic to send a language prefix/suffix regex for non aliased paths.
$lgregex = '';
if ($url_locale) {
$lgregex = '[a-z]{2}\/';
}
elseif ($url_suffix) {
$lgregex = '_[a-z]{2}';
}
// Get the languages the node is translated into (entity translation).
if (module_exists('entity_translation') && entity_translation_enabled('node', $node)) {
$handler = entity_translation_get_handler('node', $node);
$translations = $handler->getTranslations();
$lang_codes = array_keys($translations->data);
$all_languages = entity_translation_languages('node', $node);
// Small workaround for undefined language.
if (count($lang_codes) === 1 && LANGUAGE_NONE == $lang_codes[0]) {
// Push all the languages.
$lang_codes = array_keys($all_languages);
}
foreach ($lang_codes as $code) {
if (!isset($all_languages[$code])) {
continue;
}
$alias = drupal_get_path_alias($entity_uri['path'], $code);
$original_alias = $alias;
$lang = $all_languages[$code];
// Add the prefix or suffix.
$paths[$code] = _nexteuropa_varnish_build_path($url_locale, $lang, $alias, $entity_uri);
$alias = drupal_get_path_alias($entity_uri['path'], $code);
$original_alias = $alias;
// Add the prefix or suffix.
$paths[$code] = _nexteuropa_varnish_build_path($url_locale, $all_languages[$code], $alias, $entity_uri);
}
}
else {
// Content translation.
$lang_code = entity_language('node', $node);
$enabled_languages = language_list('enabled')[1];
$alias = drupal_get_path_alias($entity_uri['path'], $lang_code);
$original_alias = $alias;
// Language is undefined, the content will show on all languages.
if (LANGUAGE_NONE == $lang_code) {
foreach ($enabled_languages as $code => $data) {
$lang = $enabled_languages[$code];
// Add the prefix or suffix.
$paths[$code] = _nexteuropa_varnish_build_path($url_locale, $lang, $alias, $entity_uri);
}
}
else {
$lang = $enabled_languages[$lang_code];
// Add the prefix or suffix.
$paths[$lang_code] = _nexteuropa_varnish_build_path($url_locale, $lang, $alias, $entity_uri);
}
}
// Get the node\/nid.
$paths['unaliased'] = $entity_uri['path'];
// Add escaped alias.
// Example content\/my\-page.
$paths['escaped_alias'] = $original_alias;
$paths = array_map('_nexteuropa_varnish_escape', $paths);
// Add regex prefix or suffix if needed.
// Example node\/nid_[a-z]{2}.
$paths['full_unaliased'] = $url_suffix ? $paths['unaliased'] . $lgregex : $lgregex . $paths['unaliased'];
}
return $paths;
}
/**
* Custom callback to escape all path at the end of the collection.
*
* @param string $path
* The iterative path to escape.
*
* @return string
* The escaped string.
*/
function _nexteuropa_varnish_escape($path) {
return preg_quote($path, '/');
}
/**
* Custom function returns alias depending of language & translation mechanism.
*
* @param string|bool $url_locale
* FALSE if locale-url language negotiation is not enabled,
* 'language-url' otherwise.
* @param object $lang
* The current node's language object.
* @param string $alias
* The current node's path alias.
* @param array $entity_uri
* The array containing the 'path' and 'options' keys used to build the URI of
* the entity.
*
* @return string
* The path incuding the prefix or suffix.
*/
function _nexteuropa_varnish_build_path($url_locale, $lang, $alias, $entity_uri) {
$options = $entity_uri['options'];
$altered_options = $options + array('language' => $lang) + array('external' => FALSE);
// Add the suffix/prefix depending negociation setup.
drupal_alter('url_outbound', $alias, $altered_options, $entity_uri['path']);
// If we don't use prefix, outbound did the job, if not push prefix.
if (!$url_locale) {
$path = $alias;
}
else {
$path = $altered_options['prefix'] . $alias;
}
return $path;
}
/**
* Gets node's paths that have changed since last time.
*
* @param object $node
* The node object.
*
* @return array
* The list of changed paths.
*/
function _nexteuropa_varnish_get_updated_node_paths($node) {
// Node old_paths are injected in nexteuropa_varnish_node_presave().
$old_paths = array();
if (isset($node->nexteuropa_varnish_old_paths)) {
$old_paths = $node->nexteuropa_varnish_old_paths;
}
$old_paths = array_map('_nexteuropa_varnish_trim_base_path', $old_paths);
$new_paths = _nexteuropa_varnish_get_node_paths($node);
$new_paths = array_map('_nexteuropa_varnish_trim_base_path', $new_paths);
return _nexteuropa_varnish_compare_node_path_revisions($old_paths, $new_paths);
}
/**
* Compare the old node paths with the new ones.
*
* @param array $old_paths
* The list of previous node paths.
* @param array $new_paths
* The list of new node paths.
*
* @return array
* The list of old paths that have been changed; otherwise, it returns an
* empty array.
*/
function _nexteuropa_varnish_compare_node_path_revisions($old_paths, $new_paths) {
if (empty($old_paths)) {
return array();
}
$diff_paths = array();
foreach ($old_paths as $lang => $old_path) {
if (!isset($new_paths[$lang])) {
$diff_paths[] = $old_path;
continue;
}
if ($old_path !== $new_paths[$lang]) {
$diff_paths[] = $old_path;
}
}
return $diff_paths;
}
/**
* Prepares the list of paths and sends them to Varnish.
*
* @param object $node
* The node object for which paths are processed.
* @param array $updated_node_paths
* The list of node's paths set in the previous revision.
*/
function _nexteuropa_varnish_process_paths_sending($node, $updated_node_paths = array()) {
$paths = _nexteuropa_varnish_get_paths_to_purge($node);
$updated_node_paths = array_merge($updated_node_paths, $paths);
if (!empty($updated_node_paths)) {
$updated_node_paths = array_unique($updated_node_paths);
$updated_node_paths = array_filter($updated_node_paths);
_nexteuropa_varnish_purge_paths($updated_node_paths);
}
}
/**
* Determines if purge rules are set for a specific node.
*
* @param object $node
* The node object.
*
* @return bool
* True, if at least a rule is set.
*/
function nexteuropa_varnish_node_has_rules($node) {
if (variable_get('nexteuropa_varnish_default_purge_rule', FALSE)) {
// If the default rule is set, then the node has a defined rule!
return TRUE;
}
$rules = nexteuropa_varnish_get_node_purge_rules($node);
return !empty($rules);
}
/**
* Determines if the purge mechanism disabling must be forced temporarily.
*
* It is based on the "nexteuropa_varnish_prevent_purge" variable.
* If it is set and equals to TRUE, the mechanism is disabled.
*
* @return bool
* TRUE if the mechanism must be disabled; ortherwise FALSE.
*/
function _nexteuropa_varnish_prevent_purge() {
return variable_get('nexteuropa_varnish_prevent_purge', FALSE);
}
/**
* Determine if the full varnish purge flush can be accessible or not by a user.
*
* @return bool
* TRUE, the user can access; otherwise FALSE.
*/
function _nexteuropa_varnish_purge_all_access() {
return (!(_nexteuropa_varnish_prevent_purge()) && user_access('administer frontend cache purge rules'));
}
/**
* Sets the temporary message when the purge mechanism is disabled by force.
*
* @return bool
* TRUE if the message is set and then that means the mechanism is disabled by
* force; otherwise FALSE.
*/
function _nexteuropa_varnish_temporary_message() {
if (_nexteuropa_varnish_prevent_purge()) {
drupal_set_message(
t('The purge mechanism is temporary disabled.<br /> Purge rules are still manageable but they will not be executed until it is enabled again.'),
'warning',
FALSE
);
return TRUE;
}
return FALSE;
}
/**
* Trims the base path from the given path.
*
* @param string $path
* Path which is going to be trimmed.
* @param string $base_path
* The base path of the current Drupal site. If NULL, the function will
* use the value given by the function base_path().
*
* @return string
* Trimmed path.
*/
function _nexteuropa_varnish_trim_base_path($path, $base_path = NULL) {
if (is_null($base_path)) {
$base_path = base_path();
}
if (drupal_substr($path, 0, drupal_strlen($base_path)) === $base_path) {
$path = drupal_substr($path, drupal_strlen($base_path));
}
return $path;
}
/**
* Flushes the path on disk of a file entity.
*
* @param object $file
* The file entity.
*/
function _nexteuropa_varnish_flush_file(&$file) {
if (_nexteuropa_varnish_prevent_purge()) {
return;
}
$scheme = file_uri_scheme($file->uri);
$base_name = drupal_basename($file->uri);
if ($scheme !== FALSE && file_stream_wrapper_valid_scheme($scheme) === TRUE) {
// Get path on filesystem.
$wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
_nexteuropa_varnish_purge_paths(array(
'escaped_alias' => preg_quote($wrapper->getDirectoryPath($file) . '/' . $base_name, '/'),
));
}
}