path.module 13.1 KB
Newer Older
Dries's avatar
Dries committed
1
2
3
<?php
/* $Id$ */

Dries's avatar
   
Dries committed
4
5
6
7
8
/**
 * @file
 * Enables users to rename URLs.
 */

9
10
11
12
13
/**
 * Implementation of hook_help().
 */
function path_help($section) {
  switch ($section) {
Dries's avatar
   
Dries committed
14
    case 'admin/modules#description':
Dries's avatar
   
Dries committed
15
      return t('Enables users to rename URLs.');
16
    case 'admin/path':
Dries's avatar
   
Dries committed
17
      return 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.");
18
    case 'admin/path/add':
Dries's avatar
   
Dries committed
19
      return t('Enter the path you wish to create the alias for, followed by the name of the new alias.');
20
21
22
23
24
25
    case 'admin/help#path':
      return t("
<h3>Background</h3>
<p>A very powerful feature of Drupal is the ability to have control over all paths. The path module is the tool that provides this functionality and is part of the basic Drupal installation, although it is not enabled by default. Some examples of re-mapping paths are:</p>
<pre>
user/login => login
Dries's avatar
Dries committed
26

27
image/tid/16 => store
Dries's avatar
Dries committed
28

Dries's avatar
   
Dries committed
29
taxonomy/term/7+19+20+21 => store/products/whirlygigs
Dries's avatar
Dries committed
30

Dries's avatar
   
Dries committed
31
node/3 => contact
32
33
</pre>
<p>This functionality integrates seamlessly into node forms and also provides the administrator an interface to view all aliases that have been created.</p>
Dries's avatar
   
Dries committed
34
35
36
37
38
39
40
41
<p>Aliases have a many to one relationship with their original Drupal URLs. In other words you can have many different aliases map to a single path. An example of where a multiple aliases come in handy is creating a standard RSS feed URL:</p>

<pre>
node/feed => rss.xml
node/feed => index.rdf
</pre>

<p>When Drupal generates links for a path with multiple aliases it will choose the first alias created per system URL.  So in our above example, Drupal would use rss.xml as the default alias rather than index.rdf. To change this behavior, delete the aliases for node/feed and create the index.rdf alias before rss.xml.</p>
Dries's avatar
Dries committed
42

43
44
45
<h3>Permissions</h3>
<p>Two permissions are related to URL aliasing: <em>create url aliases</em> and <em>administer url aliases</em>.</p>
<ol><li><strong>create url aliases</strong> - Allows users to create aliases for nodes. Enabling this permission will display a path field to the user in any node form, allowing them to enter an alias for that node. They will be able to edit/delete the alias after it is created using the same form.</li><li><strong>administer url aliases</strong> - Allows users to access the alias administration interface. They must also have the <em>access administration pages</em> permission set as well. This interface displays all aliases and provides a way to create and modify them. This is also the location to build aliases for things other than nodes. For example, you can create an alias for a taxonomy URL or even re-map the admin path (although the original admin path will still be accessible since aliases do not cancel out original paths).</li></ol>
Dries's avatar
   
Dries committed
46

47
48
49
50
51
<h3>Mass URL aliasing</h3>
<p>Drupal also comes with user defined mass URL aliasing capabilities. You might like to see completely different URLs used by Drupal, or even URLs translated to the visitors' native language, in which case this feature is handy. Only an administrator with access to the website source code can set up this kind of aliases. You can define a <code>conf_url_rewrite</code> function in conf.php, following this example:</p>
<pre>
function conf_url_rewrite(\$path, \$mode = 'incoming') {
  if (\$mode == 'incoming') { // URL coming from a client
Dries's avatar
   
Dries committed
52
    return preg_replace('!^display/(\\d+)\$!', 'node/\\1', \$path);
53
54
  }
  else { // URL going out to a client
Dries's avatar
   
Dries committed
55
    \$aliased = preg_replace('!^node/(\\d+)\$!', 'display/\\1', \$path);
56
57
58
59
    if (\$aliased != \$path) { return \$aliased; }
  }
}
</pre>
Dries's avatar
   
Dries committed
60
<p>This function will shorten every <code>node/\$node_id</code> type of URL to <code>display/\$node_id</code>. Individual URL aliases defined on the browser interface of Drupal take precedence, so if you have the 'contact' page alias from the example above, then the <code>display/3</code> alias will not be effective when outgoing links are created. Incoming URLs however always work with the mass URL aliased variant. Only the 'incoming' and 'outgoing' modes are supposed to be supported by your <code>conf_url_rewrite</code> function.</p>
Dries's avatar
   
Dries committed
61
<p>You cannot only use this feature to shorten the URLs, or to translate them to you own language, but also to add completely new subURLs to an already existing module's URL space, or to compose a bunch of existing stuff together to a common URL space. You can create a <code>news</code> section for example aliasing nodes and taxonomy overview pages falling under a 'news' vocabulary, thus having <code>news/15</code> and <code>news/sections/3</code> instead of <code>node/15</code> and <code>taxonomy/term/3</code>. You need extensive knowledge of Drupal's inner workings and regular expressions though to make such advanced aliases.</p>");
62
63
  }
}
Dries's avatar
   
Dries committed
64

65
/**
Dries's avatar
   
Dries committed
66
 * Implementation of hook_menu().
67
 */
Dries's avatar
   
Dries committed
68
69
function path_menu() {
  $items = array();
Dries's avatar
   
Dries committed
70
  $items[] = array('path' => 'admin/path', 'title' => t('url aliases'),
Dries's avatar
   
Dries committed
71
72
73
74
75
76
77
78
79
80
    'callback' => 'path_admin',
    'access' => user_access('administer url aliases'));
  $items[] = array('path' => 'admin/path/edit', 'title' => t('edit alias'),
    'callback' => 'path_admin_edit',
    'access' => user_access('administer url aliases'),
    'type' => MENU_CALLBACK);
  $items[] = array('path' => 'admin/path/delete', 'title' => t('delete alias'),
    'callback' => 'path_admin_delete',
    'access' => user_access('administer url aliases'),
    'type' => MENU_CALLBACK);
Dries's avatar
   
Dries committed
81
82
83
  $items[] = array('path' => 'admin/path/list', 'title' => t('list'),
    'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
  $items[] = array('path' => 'admin/path/add', 'title' => t('add'),
Dries's avatar
   
Dries committed
84
85
86
87
    'callback' => 'path_admin_edit',
    'access' => user_access('administer url aliases'),
    'type' => MENU_LOCAL_TASK);
  return $items;
88
}
Dries's avatar
   
Dries committed
89

90
91
92
93
94
95
96
97
98
99
100
101
/**
 * Menu callback; presents an overview of all URL aliases.
 */
function path_admin() {
  print theme('page', path_overview());
}

/**
 * Menu callback; handles pages for creating and editing URL aliases.
 */
function path_admin_edit($pid = 0) {
  if ($_POST['op'] == t('Create new alias') || $_POST['op'] == t('Update alias')) {
Dries's avatar
   
Dries committed
102
103
104
105
106
107
    $output = path_save($_POST['edit']);
  }
  elseif ($pid) {
    $alias = path_load($pid);
    $title = $alias['dst'];
    $output = path_form(path_load($pid));
Dries's avatar
Dries committed
108
  }
109
  else {
Dries's avatar
   
Dries committed
110
    $output = path_form();
111
  }
Dries's avatar
   
Dries committed
112
113

  print theme('page', $output, $title);
114
}
Dries's avatar
   
Dries committed
115

116
117
118
119
/**
 * Menu callback; handles deletion of an URL alias.
 */
function path_admin_delete($pid = 0) {
Dries's avatar
Dries committed
120
  db_query('DELETE FROM {url_alias} WHERE pid = %d', $pid);
Dries's avatar
   
Dries committed
121
  drupal_set_message(t('The alias has been deleted.'));
Dries's avatar
Dries committed
122
  drupal_goto('admin/path');
123
124
125
126
127
}

/**
 * Set an aliased path for a given Drupal path, preventing duplicates.
 */
Dries's avatar
   
Dries committed
128
function path_set_alias($path = NULL, $alias = NULL, $pid = NULL) {
Dries's avatar
   
Dries committed
129
  if ($path && !$alias) {
Dries's avatar
   
Dries committed
130
    db_query("DELETE FROM {url_alias} WHERE src = '%s'", $path);
Dries's avatar
   
Dries committed
131
132
133
    drupal_rebuild_path_map();
  }
  else if (!$path && $alias) {
Dries's avatar
   
Dries committed
134
    db_query("DELETE FROM {url_alias} WHERE dst = '%s'", $alias);
Dries's avatar
   
Dries committed
135
136
137
    drupal_rebuild_path_map();
  }
  else if ($path && $alias) {
Dries's avatar
   
Dries committed
138
139
    $path_count = db_result(db_query("SELECT COUNT(src) FROM {url_alias} WHERE src = '%s'", $path));
    $alias_count = db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s'", $alias));
Dries's avatar
   
Dries committed
140
141
142

    // We have an insert:
    if ($path_count == 0 && $alias_count == 0) {
143
      db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", $path, $alias);
Dries's avatar
   
Dries committed
144
145
      drupal_rebuild_path_map();
    }
Dries's avatar
   
Dries committed
146
147
148
149
150
151
152
    else if ($path_count >= 1 && $alias_count == 0) {
      if ($pid) {
        db_query("UPDATE {url_alias} SET dst = '%s', src = '%s' WHERE pid = %d", $alias, $path, $pid);
      }
      else {
        db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", $path, $alias);
      }
Dries's avatar
   
Dries committed
153
154
155
      drupal_rebuild_path_map();
    }
    else if ($path_count == 0 && $alias_count == 1) {
Dries's avatar
   
Dries committed
156
      db_query("UPDATE {url_alias} SET src = '%s' WHERE dst = '%s'", $path, $alias);
Dries's avatar
   
Dries committed
157
158
159
160
161
162
163
164
165
      drupal_rebuild_path_map();
    }
    else if ($path_count == 1 && $alias_count == 1) {
      // This will delete the path that alias was originally pointing to:
      path_set_alias(NULL, $alias);
      path_set_alias($path);
      path_set_alias($path, $alias);
    }
  }
Dries's avatar
Dries committed
166
167
}

168
169
170
171
/**
 * Return a form for editing or creating an individual URL alias.
 */
function path_form($edit = '') {
Dries's avatar
Dries committed
172

Dries's avatar
   
Dries committed
173
  $form .= form_textfield(t('Existing system path'), 'src', $edit['src'], 50, 64, t('Specify the existing path you wish to alias. For example: node/28, forum/1, taxonomy/term/1+2.'));
174
  $form .= form_textfield(t('New path alias'), 'dst', $edit['dst'], 50, 64, 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.'));
Dries's avatar
Dries committed
175

176
177
178
  if ($edit['pid']) {
    $form .= form_hidden('pid', $edit['pid']);
    $form .= form_submit(t('Update alias'));
Dries's avatar
   
Dries committed
179
180
  }
  else {
181
    $form .= form_submit(t('Create new alias'));
Dries's avatar
   
Dries committed
182
183
184
  }

  return form($form);
Dries's avatar
Dries committed
185
186
}

Dries's avatar
   
Dries committed
187
/**
188
189
190
191
 * Implementation of hook_nodeapi().
 *
 * Allows URL aliases for nodes to be specified at node edit time rather
 * than through the administrative interface.
Dries's avatar
   
Dries committed
192
 */
Dries's avatar
   
Dries committed
193
function path_nodeapi(&$node, $op, $arg) {
194
  if (user_access('create url aliases') || user_access('administer url aliases')) {
Dries's avatar
Dries committed
195

Dries's avatar
   
Dries committed
196
    switch ($op) {
197
      case 'validate':
Dries's avatar
   
Dries committed
198
199
200
        // is_null provides a mechanism for us to determine if this is the first
        // viewing of the form.  If it is the first time, load the alias, if it isn't
        // (i.e., user has clicked preview) let them work with their current form alias.
201
        if (is_null($node->path)) {
Dries's avatar
   
Dries committed
202
          $path = "node/$node->nid";
203
204
205
206
          $alias = drupal_get_path_alias($path);
          if ($alias != $path) {
            $node->path = $alias;
          }
Dries's avatar
   
Dries committed
207
208
        }
        else {
209
210
          $node->path = trim($node->path);
          if ($node->path && !valid_url($node->path)) {
Dries's avatar
   
Dries committed
211
            form_set_error('path', t('The path is invalid.'));
Dries's avatar
   
Dries committed
212
          }
Dries's avatar
   
Dries committed
213
          else if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s' AND src != '%s'", $node->path, "node/$node->nid"))) {
Dries's avatar
   
Dries committed
214
            form_set_error('path', t('The path is already in use.'));
Dries's avatar
   
Dries committed
215
216
217
          }
        }
        break;
Dries's avatar
Dries committed
218

219
      case 'form pre':
Dries's avatar
   
Dries committed
220
221
222
223
224
        $output = form_textfield(t('Path alias'), 'path', $node->path, 60, 250, 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 ($node->path) {
          $output .= form_hidden('pid', db_result(db_query("SELECT pid FROM {url_alias} WHERE dst = '%s'", $node->path)));
        }
        return $output;
Dries's avatar
   
Dries committed
225

226
227
228
      case 'insert':
        // Don't try to insert if path is NULL.  We may have already set
        // the alias ahead of time.
Dries's avatar
   
Dries committed
229
        if ($node->path) {
Dries's avatar
   
Dries committed
230
          path_set_alias("node/$node->nid", $node->path);
Dries's avatar
   
Dries committed
231
232
        }
        break;
233
      case 'update':
Dries's avatar
   
Dries committed
234
        path_set_alias("node/$node->nid", $node->path, $node->pid);
Dries's avatar
   
Dries committed
235
236
        break;

237
      case 'delete':
Dries's avatar
   
Dries committed
238
        $path = "node/$node->nid";
239
240
        if (drupal_get_path_alias($path) != $path) {
          path_set_alias($path);
Dries's avatar
   
Dries committed
241
242
243
        }
        break;
    }
Dries's avatar
Dries committed
244
245
246
  }
}

247
248
249
/**
 * Implementation of hook_perm().
 */
Dries's avatar
Dries committed
250
function path_perm() {
251
  return array('create url aliases', 'administer url aliases');
Dries's avatar
Dries committed
252
253
}

254
255
256
/**
 * Return a listing of all defined URL aliases.
 */
Dries's avatar
Dries committed
257
function path_overview() {
258
  $sql = 'SELECT * FROM {url_alias}';
Dries's avatar
Dries committed
259
  $header = array(
Dries's avatar
   
Dries committed
260
261
262
    array('data' => t('Alias'), 'field' => 'dst', 'sort' => 'asc'),
    array('data' => t('System'), 'field' => 'src'),
    array('data' => t('Operations'), 'colspan' => 2)
Dries's avatar
Dries committed
263
264
265
266
267
  );
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 50);

  while ($data = db_fetch_object($result)) {
268
    $rows[] = array($data->dst, $data->src, l(t('edit'), "admin/path/edit/$data->pid"), l(t('delete'), "admin/path/delete/$data->pid"));
Dries's avatar
Dries committed
269
270
  }

271
272
  if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
    $rows[] = array(array('data' => $pager, 'colspan' => '4'));
Dries's avatar
Dries committed
273
274
  }

Dries's avatar
   
Dries committed
275
  if (!$rows) {
276
    $rows[] = array(array('data' => t('No URL aliases available.'), 'colspan' => '4'));
Dries's avatar
   
Dries committed
277
278
  }

279
  return theme('table', $header, $rows);
Dries's avatar
Dries committed
280
281
}

282
283
284
/**
 * Fetch a specific URL alias from the database.
 */
Dries's avatar
   
Dries committed
285
function path_load($pid) {
286
  return db_fetch_array(db_query('SELECT * FROM {url_alias} WHERE pid = %d', $pid));
Dries's avatar
   
Dries committed
287
}
Dries's avatar
Dries committed
288

289
290
291
/**
 * Verify that a new URL alias is valid, and save it to the database.
 */
Dries's avatar
   
Dries committed
292
function path_save($edit) {
293
294
295
  $src = $edit['src'];
  $dst = $edit['dst'];
  $pid = $edit['pid'];
Dries's avatar
Dries committed
296

Dries's avatar
   
Dries committed
297
  if (!valid_url($src)) {
Dries's avatar
   
Dries committed
298
    form_set_error('src', t('The system path %path is invalid.', array('%path' => "<em>$src</em>")));
Dries's avatar
Dries committed
299
300
  }

Dries's avatar
   
Dries committed
301
  if (!valid_url($dst)) {
Dries's avatar
   
Dries committed
302
    form_set_error('dst', t('The alias %alias is invalid.', array('%alias' => "<em>$dst</em>")));
Dries's avatar
Dries committed
303
304
  }

305
  if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE pid != %d AND dst = '%s'", $pid, $dst))) {
Dries's avatar
   
Dries committed
306
    form_set_error('dst', t('The alias %alias is already in use.', array('%alias' => "<em>$dst</em>")));
Dries's avatar
   
Dries committed
307
  }
Dries's avatar
Dries committed
308

Dries's avatar
   
Dries committed
309
310
  if (form_get_errors()) {
    return path_form($edit);
Dries's avatar
Dries committed
311
  }
Dries's avatar
   
Dries committed
312
  else {
Dries's avatar
   
Dries committed
313
    path_set_alias($src, $dst, $pid);
Dries's avatar
Dries committed
314

Dries's avatar
   
Dries committed
315
    drupal_set_message(t('The alias has been saved.'));
Dries's avatar
   
Dries committed
316
    drupal_goto('admin/path');
Dries's avatar
   
Dries committed
317
  }
Dries's avatar
Dries committed
318
319
320
}

?>