path.module 15.3 KB
Newer Older
Steven Wittens's avatar
Steven Wittens committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
// $Id$

/**
 * @file
 * Enables users to rename URLs.
 */

/**
 * Implementation of hook_help().
 */
function path_help($section) {
  switch ($section) {
    case 'admin/help#path':
      $output = '<p>'. t('The path module allows you to specify aliases for Drupal URLs. Such aliases improve readability of URLs for your users and may help internet search engines to index your content more effectively. More than one alias may be created for a given page.') .'</p>';
      $output .= t('<p>Some examples of URL aliases are:</p>
<ul>
<li>user/login =&gt; login</li>
<li>image/tid/16 =&gt; store</li>
<li>taxonomy/term/7+19+20+21 =&gt; store/products/whirlygigs</li>
<li>node/3 =&gt; contact</li>
</ul>
');
24
      $output .= '<p>'. t('The path module enables an extra field for aliases in all node input and editing forms (when users have the appropriate permissions). It also provides an interface to view and edit all URL aliases. The two permissions related to URL aliasing are "administer url aliases" and "create url aliases". ') .'</p>';
Steven Wittens's avatar
Steven Wittens committed
25
26
27
28
      $output .= '<p>'. t('This module also comes with user-defined mass URL aliasing capabilities, which is useful if you wish to uniformly use URLs different from the default. For example, you may want to have your URLs presented in a different language. Access to the Drupal source code on the web server is required to set up these kinds of aliases. ') .'</p>';
      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@path">Path page</a>.', array('@path' => 'http://drupal.org/handbook/modules/path/')) .'</p>';
      return $output;
    case 'admin/build/path':
29
    case 'admin/build/path/list':
30
      return '<p>'. t("Drupal provides users complete control over URLs through aliasing. This feature is typically used to make URLs human-readable or easy to remember. For example, one could map the relative URL 'node/1' onto 'about'. Each system path can have multiple aliases.") .'</p>';
Steven Wittens's avatar
Steven Wittens committed
31
    case 'admin/build/path/add':
32
      return '<p>'. t('Enter the path you wish to create the alias for, followed by the name of the new alias.') .'</p>';
Steven Wittens's avatar
Steven Wittens committed
33
34
35
36
37
38
  }
}

/**
 * Implementation of hook_menu().
 */
39
40
function path_menu() {
  $items['admin/build/path'] = array(
41
42
    'title' => 'URL aliases',
    'description' => "Change your site's URL paths by aliasing them.",
43
    'page callback' => 'path_admin_overview',
44
45
46
    'access arguments' => array('administer url aliases'),
  );
  $items['admin/build/path/edit'] = array(
47
    'title' => 'Edit alias',
48
49
50
51
52
    'page callback' => 'drupal_get_form',
    'page arguments' => array('path_admin_edit'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/build/path/delete'] = array(
53
    'title' => 'Delete alias',
54
55
56
57
58
    'page callback' => 'drupal_get_form',
    'page arguments' => array('path_admin_delete_confirm'),
    'type' => MENU_CALLBACK,
  );
  $items['admin/build/path/list'] = array(
59
    'title' => 'List',
60
61
62
63
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/build/path/add'] = array(
64
    'title' => 'Add alias',
65
66
67
68
69
    'page callback' => 'drupal_get_form',
    'page arguments' => array('path_admin_edit'),
    'access arguments' => array('administer url aliases'),
    'type' => MENU_LOCAL_TASK,
  );
Steven Wittens's avatar
Steven Wittens committed
70
71
72
73
74
75
76
77
78
79

  return $items;
}

/**
 * Menu callback; handles pages for creating and editing URL aliases.
 */
function path_admin_edit($pid = 0) {
  if ($pid) {
    $alias = path_load($pid);
80
    drupal_set_title(check_plain($alias['dst']));
Steven Wittens's avatar
Steven Wittens committed
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    $output = path_form($alias);
  }
  else {
    $output = path_form();
  }

  return $output;
}

/**
 * Menu callback; confirms deleting an URL alias
 **/
function path_admin_delete_confirm($pid) {
  $path = path_load($pid);
  if (user_access('administer url aliases')) {
    $form['pid'] = array('#type' => 'value', '#value' => $pid);
    $output = confirm_form($form,
  t('Are you sure you want to delete path alias %title?', array('%title' => $path['dst'])),
99
   isset($_GET['destination']) ? $_GET['destination'] : 'admin/build/path', t('This action cannot be undone.'),
Steven Wittens's avatar
Steven Wittens committed
100
101
102
103
104
105
106
107
  t('Delete'), t('Cancel') );
  }
  return $output;
}

/**
 * Execute URL alias deletion
 **/
108
function path_admin_delete_confirm_submit($form_values, $form, &$form_state) {
Steven Wittens's avatar
Steven Wittens committed
109
110
  if ($form_values['confirm']) {
    path_admin_delete($form_values['pid']);
111
112
    $form_state['redirect'] = 'admin/build/path';
    return;
Steven Wittens's avatar
Steven Wittens committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
  }
}

/**
 * Post-confirmation; delete an URL alias.
 */
function path_admin_delete($pid = 0) {
  db_query('DELETE FROM {url_alias} WHERE pid = %d', $pid);
  drupal_set_message(t('The alias has been deleted.'));
}

/**
 * Set an aliased path for a given Drupal path, preventing duplicates.
 */
127
function path_set_alias($path = NULL, $alias = NULL, $pid = NULL, $language = '') {
Steven Wittens's avatar
Steven Wittens committed
128
  if ($path && !$alias) {
129
130
    // Delete based on path
    db_query("DELETE FROM {url_alias} WHERE src = '%s' AND language = '%s'", $path, $language);
Steven Wittens's avatar
Steven Wittens committed
131
132
133
    drupal_clear_path_cache();
  }
  else if (!$path && $alias) {
134
135
    // Delete based on alias
    db_query("DELETE FROM {url_alias} WHERE dst = '%s' AND language = '%s'", $alias, $language);
Steven Wittens's avatar
Steven Wittens committed
136
137
138
139
    drupal_clear_path_cache();
  }
  else if ($path && $alias) {
    $path = urldecode($path);
140
    $path_count = db_result(db_query("SELECT COUNT(src) FROM {url_alias} WHERE src = '%s' AND language = '%s'", $path, $language));
Steven Wittens's avatar
Steven Wittens committed
141
    $alias = urldecode($alias);
142
    // Alias count can only be 0 or 1.
143
    $alias_count = db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s' AND language = '%s'", $alias, $language));
Steven Wittens's avatar
Steven Wittens committed
144

145
    if ($alias_count == 0) {
Steven Wittens's avatar
Steven Wittens committed
146
      if ($pid) {
147
148
        // Existing path changed data
        db_query("UPDATE {url_alias} SET src = '%s', dst = '%s', language = '%s' WHERE pid = %d", $path, $alias, $language, $pid);
Steven Wittens's avatar
Steven Wittens committed
149
150
      }
      else {
151
152
        // No such alias yet in this language
        db_query("INSERT INTO {url_alias} (src, dst, language) VALUES ('%s', '%s', '%s')", $path, $alias, $language);
Steven Wittens's avatar
Steven Wittens committed
153
154
      }
    }
155
156
157
158
    // The alias exists.
    else {
      // This path has no alias yet, so we redirect the alias here.
      if ($path_count == 0) {
159
        db_query("UPDATE {url_alias} SET src = '%s' WHERE dst = '%s' AND language = '%s'", $path, $alias, $language);
160
161
162
      }
      else {
        // This will delete the path that alias was originally pointing to.
163
        path_set_alias(NULL, $alias, NULL, $language);
164
        // This will remove the current aliases of the path.
165
166
        path_set_alias($path, NULL, NULL, $language);
        path_set_alias($path, $alias, NULL, $language);
167
      }
Steven Wittens's avatar
Steven Wittens committed
168
    }
169
170
    if ($alias_count == 0 || $path_count == 0) {
      drupal_clear_path_cache();
Steven Wittens's avatar
Steven Wittens committed
171
172
173
174
175
176
177
    }
  }
}

/**
 * Return a form for editing or creating an individual URL alias.
 */
178
function path_form($edit = array('src' => '', 'dst' => '', 'language' => '', 'pid' => NULL)) {
179
180
  $form['#submit'][] = 'path_form_submit';
  $form['#validate'][] = 'path_form_validate';
181
  $form['#alias'] = $edit;
Steven Wittens's avatar
Steven Wittens committed
182
183
184
185
186
187
188
189

  $form['src'] = array(
    '#type' => 'textfield',
    '#title' => t('Existing system path'),
    '#default_value' => $edit['src'],
    '#maxlength' => 64,
    '#size' => 45,
    '#description' => t('Specify the existing path you wish to alias. For example: node/28, forum/1, taxonomy/term/1+2.'),
190
    '#field_prefix' => url(NULL, array('absolute' => TRUE)) . (variable_get('clean_url', 0) ? '' : '?q=')
Steven Wittens's avatar
Steven Wittens committed
191
192
193
  );
  $form['dst'] = array(
    '#type' => 'textfield',
194
    '#title' => t('Path alias'),
Steven Wittens's avatar
Steven Wittens committed
195
196
197
198
    '#default_value' => $edit['dst'],
    '#maxlength' => 64,
    '#size' => 45,
    '#description' => t('Specify an alternative path by which this data can be accessed. For example, type "about" when writing an about page. Use a relative path and don\'t add a trailing slash or the URL alias won\'t work.'),
199
    '#field_prefix' => url(NULL, array('absolute' => TRUE)) . (variable_get('clean_url', 0) ? '' : '?q=')
Steven Wittens's avatar
Steven Wittens committed
200
  );
201
202
203
204
205
  // This will be a hidden value unless locale module is enabled
  $form['language'] = array(
    '#type' => 'value',
    '#value' => $edit['language']
  );
Steven Wittens's avatar
Steven Wittens committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
  if ($edit['pid']) {
    $form['pid'] = array('#type' => 'hidden', '#value' => $edit['pid']);
    $form['submit'] = array('#type' => 'submit', '#value' => t('Update alias'));
  }
  else {
    $form['submit'] = array('#type' => 'submit', '#value' => t('Create new alias'));
  }

  return $form;
}

/**
 * Implementation of hook_nodeapi().
 *
 * Allows URL aliases for nodes to be specified at node edit time rather
 * than through the administrative interface.
 */
function path_nodeapi(&$node, $op, $arg) {
  if (user_access('create url aliases') || user_access('administer url aliases')) {
    switch ($op) {
      case 'validate':
        $node->path = trim($node->path);
228
229
        $language = isset($node->language) ? $node->language : '';
        if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s' AND src != '%s' AND language = '%s'", $node->path, "node/$node->nid", $language))) {
Steven Wittens's avatar
Steven Wittens committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
          form_set_error('path', t('The path is already in use.'));
        }
        break;

      case 'load':
        $path = "node/$node->nid";
        // We don't use drupal_get_path_alias() to avoid custom rewrite functions.
        // We only care about exact aliases.
        $result = db_query("SELECT dst FROM {url_alias} WHERE src = '%s'", $path);
        if (db_num_rows($result)) {
          $node->path = db_result($result);
        }
        break;

      case 'insert':
        // Don't try to insert if path is NULL. We may have already set
        // the alias ahead of time.
        if ($node->path) {
          path_set_alias("node/$node->nid", $node->path);
        }
        break;

      case 'update':
253
        path_set_alias("node/$node->nid", isset($node->path) ? $node->path : NULL, isset($node->pid) ? $node->pid : NULL);
Steven Wittens's avatar
Steven Wittens committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
        break;

      case 'delete':
        $path = "node/$node->nid";
        if (drupal_get_path_alias($path) != $path) {
          path_set_alias($path);
        }
        break;
    }
  }
}

/**
 * Implementation of hook_form_alter().
 */
269
function path_form_alter(&$form, $form_id) {
270
  if (isset($form['type']) && isset($form['#node']) && $form['type']['#value'] .'_node_form' == $form_id) {
271
    $path = isset($form['#node']->path) ? $form['#node']->path : NULL;
Steven Wittens's avatar
Steven Wittens committed
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
    $form['path'] = array(
      '#type' => 'fieldset',
      '#title' => t('URL path settings'),
      '#collapsible' => TRUE,
      '#collapsed' => empty($path),
      '#access' => user_access('create url aliases'),
      '#weight' => 30,
    );
    $form['path']['path'] = array(
      '#type' => 'textfield',
      '#default_value' => $path,
      '#maxlength' => 250,
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#description' => t('Optionally specify an alternative URL by which this node can be accessed. For example, type "about" when writing an about page. Use a relative path and don\'t add a trailing slash or the URL alias won\'t work.'),
    );
    if ($path) {
      $form['path']['pid'] = array(
        '#type' => 'value',
        '#value' => db_result(db_query("SELECT pid FROM {url_alias} WHERE dst = '%s'", $path))
      );
    }
  }
}


/**
 * Implementation of hook_perm().
 */
function path_perm() {
  return array('create url aliases', 'administer url aliases');
}

/**
 * Return a listing of all defined URL aliases.
307
308
 * When filter key passed, perform a standard search on the given key,
 * and return the list of matching URL aliases.
Steven Wittens's avatar
Steven Wittens committed
309
 */
310
311
312
function path_admin_overview($keys = NULL) {
  // Add the filter form above the overview table.
  $output = drupal_get_form('path_admin_filter_form', $keys);
313
314
315
316
  // Enable language column if locale is enabled or if we have any alias with language
  $count = db_result(db_query("SELECT COUNT(*) FROM {url_alias} WHERE language != ''"));
  $multilanguage = (module_exists('locale') || $count);

317
318
319
320
321
322
323
324
  if ($keys) {
    // Replace wildcards with MySQL/PostgreSQL wildcards.
    $keys = preg_replace('!\*+!', '%', $keys);
    $sql = "SELECT * FROM {url_alias} WHERE dst LIKE '%%%s%%'";
  }
  else {
    $sql = 'SELECT * FROM {url_alias}';
  }
Steven Wittens's avatar
Steven Wittens committed
325
326
327
328
329
  $header = array(
    array('data' => t('Alias'), 'field' => 'dst', 'sort' => 'asc'),
    array('data' => t('System'), 'field' => 'src'),
    array('data' => t('Operations'), 'colspan' => '2')
  );
330
331
332
333
  if ($multilanguage) {
    $header[3] = $header[2];
    $header[2] = array('data' => t('Language'), 'field' => 'language');
  }
Steven Wittens's avatar
Steven Wittens committed
334
  $sql .= tablesort_sql($header);
335
  $result = pager_query($sql, 50, 0 , NULL, $keys);
Steven Wittens's avatar
Steven Wittens committed
336

337
  $rows = array();
Steven Wittens's avatar
Steven Wittens committed
338
339
  $destination = drupal_get_destination();
  while ($data = db_fetch_object($result)) {
340
341
342
343
344
345
346
    $row = array(check_plain($data->dst), check_plain($data->src), l(t('edit'), "admin/build/path/edit/$data->pid", array('query' => $destination)), l(t('delete'), "admin/build/path/delete/$data->pid", array('query' => $destination)));
    if ($multilanguage) {
      $row[4] = $row[3];
      $row[3] = $row[2];
      $row[2] = module_invoke('locale', 'language_name', $data->language);
    }
    $rows[] = $row;
Steven Wittens's avatar
Steven Wittens committed
347
348
  }

349
  if (empty($rows)) {
350
351
    $empty_message = $keys ? t('No URL aliases found.') : t('No URL aliases available.') ;
    $rows[] = array(array('data' => $empty_message, 'colspan' => ($multilanguage ? 5 : 4)));
Steven Wittens's avatar
Steven Wittens committed
352
353
  }

354
  $output .= theme('table', $header, $rows);
Steven Wittens's avatar
Steven Wittens committed
355
  $output .= theme('pager', NULL, 50, 0);
356

Steven Wittens's avatar
Steven Wittens committed
357
358
359
360
361
362
363
364
365
366
367
368
369
  return $output;
}

/**
 * Fetch a specific URL alias from the database.
 */
function path_load($pid) {
  return db_fetch_array(db_query('SELECT * FROM {url_alias} WHERE pid = %d', $pid));
}

/**
 * Verify that a new URL alias is valid
 */
370
function path_form_validate($form_values, $form, &$form_state) {
Steven Wittens's avatar
Steven Wittens committed
371
372
  $src = $form_values['src'];
  $dst = $form_values['dst'];
373
  $pid = isset($form_values['pid']) ? $form_values['pid'] : 0;
374
375
  // Language is only set if locale module is enabled, otherwise save for all languages.
  $language = isset($form_values['language']) ? $form_values['language'] : '';
Steven Wittens's avatar
Steven Wittens committed
376

377
378
  if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE pid != %d AND dst = '%s' AND language = '%s'", $pid, $dst, $language))) {
    form_set_error('dst', t('The alias %alias is already in use in this language.', array('%alias' => $dst)));
Steven Wittens's avatar
Steven Wittens committed
379
380
381
382
383
384
  }
}

/**
 * Save a new URL alias to the database.
 */
385
function path_form_submit($form_values, $form, &$form_state) {
386
  // Language is only set if locale module is enabled
387
  path_set_alias($form_values['src'], $form_values['dst'], isset($form_values['pid']) ? $form_values['pid'] : 0, isset($form_values['language']) ? $form_values['language'] : '');
Steven Wittens's avatar
Steven Wittens committed
388
389

  drupal_set_message(t('The alias has been saved.'));
390
391
  $form_state['redirect'] = 'admin/build/path';
  return;
Steven Wittens's avatar
Steven Wittens committed
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

/**
 * Return a form to filter URL aliases.
 */
function path_admin_filter_form($keys = '') {
  $form['#attributes'] = array('class' => 'search-form');
  $form['basic'] = array('#type' => 'fieldset',
    '#title' => t('Filter aliases')
  );
  $form['basic']['inline'] = array('#prefix' => '<div class="container-inline">', '#suffix' => '</div>');
  $form['basic']['inline']['filter'] = array(
    '#type' => 'textfield',
    '#title' => '',
    '#default_value' => $keys,
    '#maxlength' => 64,
    '#size' => 25,
  );
  $form['basic']['inline']['submit'] = array('#type' => 'submit', '#value' => t('Filter'));

  return $form;
}

/**
 * Process filter form submission.
 */
function path_admin_filter_form_submit($form_id, $form_values) {
  return 'admin/build/path/list/'. trim($form_values['filter']);
}

/**
 * Helper function for grabbing filter keys.
 */
function path_admin_filter_get_keys() {
  // Extract keys as remainder of path
  $path = explode('/', $_GET['q'], 5);
  return count($path) == 5 ? $path[4] : '';
}