-
Notifications
You must be signed in to change notification settings - Fork 29
/
redirect.module
402 lines (366 loc) · 11.8 KB
/
redirect.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
<?php
/**
* @file
* The redirect module.
*/
/**
* @defgroup redirect_api Redirection API
* @{
* Functions related to URL redirects.
*
* @} End of "defgroup redirect_api".
*/
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\Language;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Site\Settings;
use Drupal\redirect\Entity\Redirect;
/**
* Implements hook_hook_info().
*/
function redirect_hook_info() {
$hooks = array(
'redirect_load',
'redirect_load_by_source_alter',
'redirect_access',
'redirect_prepare',
'redirect_validate',
'redirect_presave',
'redirect_insert',
'redirect_update',
'redirect_delete',
'redirect_alter',
);
return array_fill_keys($hooks, array('group' => 'redirect'));
}
/**
* Implements hook_help().
*/
function redirect_help($route_name, RouteMatchInterface $route_match) {
$output = '';
switch ($route_name) {
case 'redirect.fix_404':
$output = '<p>' . t('This page lists all paths that have resulted in 404 errors and do not yet have any redirects assigned to them.') . '</p>';
break;
}
return $output;
}
/**
* Implements hook_entity_delete().
*
* Will delete redirects based on the entity URL.
*/
function redirect_entity_delete(EntityInterface $entity) {
if (redirect_entity_has_path_field($entity)) {
redirect_delete_by_path('internal:/' . $entity->urlInfo()->getInternalPath());
redirect_delete_by_path('entity:' . $entity->getEntityTypeId() . '/' . $entity->id());
}
}
/**
* Implements hook_path_update().
*
* Will create redirect from the old path alias to the new one.
*/
function redirect_path_update(array $path) {
if (!\Drupal::config('redirect.settings')->get('auto_redirect')) {
return;
}
$original_path = $path['original'];
// Delete all redirects having the same source as this alias.
redirect_delete_by_path($path['alias'], $path['langcode'], FALSE);
if ($original_path['alias'] != $path['alias']) {
if (!redirect_repository()->findMatchingRedirect($original_path['alias'], array(), $original_path['langcode'])) {
$redirect = Redirect::create();
$redirect->setSource($original_path['alias']);
$redirect->setRedirect($path['source']);
$redirect->setLanguage($original_path['langcode']);
$redirect->setStatusCode(\Drupal::config('redirect.settings')->get('default_status_code'));
$redirect->save();
}
}
}
/**
* Implements hook_path_insert().
*/
function redirect_path_insert(array $path) {
// Delete all redirects having the same source as this alias.
redirect_delete_by_path($path['alias'], $path['langcode'], FALSE);
}
/**
* Implements hook_path_delete().
*/
function redirect_path_delete($path) {
if (!\Drupal::config('redirect.settings')->get('auto_redirect')) {
return;
}
elseif (isset($path['redirect']) && !$path['redirect']) {
return;
}
elseif (empty($path)) {
// @todo Remove this condition and allow $path to use an array type hint
// when http://drupal.org/node/1025904 is fixed.
return;
}
// Redirect from a deleted alias to the system path.
//if (!redirect_load_by_source($path['alias'], $path['language'])) {
// $redirect = new stdClass();
// redirect_create($redirect);
// $redirect->source = $path['alias'];
// $redirect->redirect = $path['source'];
// $redirect->language = $path['language'];
// redirect_save($redirect);
//}
}
/**
* Implements hook_page_build().
*
* Adds an action on 404 pages to create a redirect.
*
* @todo hook_page_build() can no longer be used for this. Find a different way.
*/
function redirect_page_build(&$page) {
if (redirect_is_current_page_404() && \Drupal::currentUser()->hasPermission('administer redirects')) {
if (!isset($page['content']['system_main']['actions'])) {
$page['content']['system_main']['actions'] = array(
'#theme' => 'links',
'#links' => array(),
'#attributes' => array('class' => array('action-links')),
'#weight' => -100,
);
}
// We cannot simply use current_path() because if a 404 path is set, then
// that value overrides whatever is in $_GET['q']. The
// drupal_deliver_html_page() function thankfully puts the original current
// path into $_GET['destination'].
$destination = drupal_get_destination();
$page['content']['system_main']['actions']['#links']['add_redirect'] = array(
'title' => t('Add URL redirect from this page to another location'),
'href' => 'admin/config/search/redirect/add',
'query' => array('source' => $destination['destination']) + drupal_get_destination(),
);
}
}
/**
* Checks if the entity has path field.
*
* @param EntityInterface $entity
* The entity to check.
*
* @return bool
* TRUE if the entity has the path field.
*/
function redirect_entity_has_path_field(EntityInterface $entity) {
if (isset($entity->path) && $entity->path instanceof FieldItemList) {
return TRUE;
}
return FALSE;
}
/**
* Gets the redirect repository service.
*
* @return \Drupal\redirect\RedirectRepository
* The repository service.
*/
function redirect_repository() {
return \Drupal::service('redirect.repository');
}
/**
* Delete any redirects associated with a path or any of its sub-paths.
*
* Given a source like 'node/1' this function will delete any redirects that
* have that specific source or any sources that match 'node/1/%'.
*
* @param string $path
* An string with an internal Drupal path.
* @param string $langcode
* (optional) If specified, limits deletion to redirects for the given
* language. Defaults to all languages.
* @param bool $match_subpaths_and_redirect
* (optional) Whether redirects with a destination to the given path and
* sub-paths should also be deleted.
*
* @ingroup redirect_api
*/
function redirect_delete_by_path($path, $langcode = NULL, $match_subpaths_and_redirect = TRUE) {
$path = ltrim($path, '/');
$query = db_select('redirect');
$query->addField('redirect', 'rid');
$query_or = db_or();
$query_or->condition('redirect_source__path', db_like($path), 'LIKE');
if ($match_subpaths_and_redirect) {
$query_or->condition('redirect_source__path', db_like($path . '/') . '%', 'LIKE');
$query_or->condition('redirect_redirect__uri', db_like($path), 'LIKE');
$query_or->condition('redirect_redirect__uri', db_like($path . '/') . '%', 'LIKE');
}
if ($langcode) {
$query->condition('language', $langcode);
}
$query->condition($query_or);
$rids = $query->execute()->fetchCol();
if ($rids) {
foreach (redirect_repository()->loadMultiple($rids) as $redirect) {
$redirect->delete();
}
}
}
/**
* Sort an array recusively.
*
* @param $array
* The array to sort, by reference.
* @param $callback
* The sorting callback to use (e.g. 'sort', 'ksort', 'asort').
*
* @return
* TRUE on success or FALSE on failure.
*/
function redirect_sort_recursive(&$array, $callback = 'sort') {
$result = $callback($array);
foreach ($array as $key => $value) {
if (is_array($value)) {
$result &= redirect_sort_recursive($array[$key], $callback);
}
}
return $result;
}
/**
* Build the URL of a redirect for display purposes only.
*/
function redirect_url($path, array $options = array(), $clean_url = NULL) {
// @todo - deal with removal of clean_url config. See
// https://drupal.org/node/1659580
if (!isset($clean_url)) {
//$clean_url = variable_get('clean_url', 0);
}
if ($path == '') {
$path = '<front>';
}
if (!isset($options['alter']) || !empty($options['alter'])) {
\Drupal::moduleHandler()->alter('redirect_url', $path, $options);
}
// The base_url might be rewritten from the language rewrite in domain mode.
if (!isset($options['base_url'])) {
// @todo - is this correct? See https://drupal.org/node/1798832.
if (isset($options['https']) && Settings::get('mixed_mode_sessions', FALSE)) {
if ($options['https'] === TRUE) {
$options['base_url'] = $GLOBALS['base_secure_url'];
$options['absolute'] = TRUE;
}
elseif ($options['https'] === FALSE) {
$options['base_url'] = $GLOBALS['base_insecure_url'];
$options['absolute'] = TRUE;
}
}
else {
$options['base_url'] = $GLOBALS['base_url'];
}
}
if (empty($options['absolute']) || url_is_external($path)) {
$url = $path;
}
else {
$url = $options['base_url'] . base_path() . $path;
}
if (isset($options['query'])) {
$url .= $clean_url ? '?' : '&';
$url .= UrlHelper::buildQuery($options['query']);
}
if (isset($options['fragment'])) {
$url .= '#' . $options['fragment'];
}
return $url;
}
function redirect_status_code_options($code = NULL) {
$codes = array(
300 => t('300 Multiple Choices'),
301 => t('301 Moved Permanently'),
302 => t('302 Found'),
303 => t('303 See Other'),
304 => t('304 Not Modified'),
305 => t('305 Use Proxy'),
307 => t('307 Temporary Redirect'),
);
return isset($codes[$code]) ? $codes[$code] : $codes;
}
/**
* Returns if the current page request is a page not found (404 status error).
*
* Why the fuck do we have to do this? Why is there not an easier way???
*
* @return
* TRUE if the current page is a 404, or FALSE otherwise.
*/
function redirect_is_current_page_404() {
return drupal_get_http_header('Status') == '404 Not Found';
}
/**
* uasort callback; Compare redirects based on language neutrality and rids.
*/
function _redirect_uasort($a, $b) {
$a_weight = isset($a->weight) ? $a->weight : 0;
$b_weight = isset($b->weight) ? $b->weight : 0;
if ($a_weight != $b_weight) {
// First sort by weight (case sensitivity).
return $a_weight > $b_weight;
}
elseif ($a->language != $b->language) {
// Then sort by language specific over language neutral.
return $a->language == Language::LANGCODE_NOT_SPECIFIED;
}
elseif (!empty($a->source_options['query']) != !empty($b->source_options['query'])) {
// Then sort by redirects that do not have query strings over ones that do.
return empty($a->source_options['query']);
}
else {
// Lastly sort by the highest redirect ID.
return $a->rid < $b->rid;
}
}
/**
* Implements hook_form_FORM_ID_alter() on behalf of locale.module.
*/
function locale_form_redirect_edit_form_alter(array &$form, FormStateInterface $form_state) {
$form['language'] = array(
'#type' => 'select',
'#title' => t('Language'),
'#options' => array(Language::LANGCODE_NOT_SPECIFIED => t('All languages')) + \Drupal::languageManager()->getLanguages(),
'#default_value' => $form['language']['#value'],
'#description' => t('A redirect set for a specific language will always be used when requesting this page in that language, and takes precedence over redirects set for <em>All languages</em>.'),
);
}
/**
* Fetch an array of redirect bulk operations.
*
* @see hook_redirect_operations()
* @see hook_redirect_operations_alter()
*/
function redirect_get_redirect_operations() {
$operations = &drupal_static(__FUNCTION__);
if (!isset($operations)) {
$operations = \Drupal::moduleHandler()->invokeAll('redirect_operations');
\Drupal::moduleHandler()->alter('redirect_operations', $operations);
}
return $operations;
}
/**
* Implements hook_redirect_operations().
*/
function redirect_redirect_operations() {
$operations['delete'] = array(
'action' => t('Delete'),
'action_past' => t('Deleted'),
'callback' => 'redirect_delete_multiple',
'confirm' => TRUE,
);
return $operations;
}
/**
* Ajax callback for the redirect link widget.
*/
function redirect_source_link_get_status_messages(array $form, FormStateInterface $form_state) {
return $form['redirect_source']['widget'][0]['status_box'];
}