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

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * Implementation of hook_help().
 */
function path_help($section) {
  switch ($section) {
    case 'admin/system/modules#description':
      return t('Enables users to create custom URLs.');
    case 'admin/path':
      return t('Drupal provides users complete control over URLs through aliasing. While the original Drupal URLs are always created and accessible, advanced users have the option to override these normal paths.');
    case 'admin/path/add':
      return t('Enter the path you wish to create the alias for, followed by the name of the new alias. Each path can be associated with only one alias.');
    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
21

22
image/tid/16 => store
Dries's avatar
Dries committed
23

24
taxonomy/page/or/7,19,20,21 => store/products/whirlygigs
Dries's avatar
Dries committed
25

26
27
28
29
node/view/3 => contact
</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>
<p>Aliases have a 1 to 1 relationship with their original Drupal URLs. In other words you cannot have an alias map to more than one path. Likewise, a Drupal URL can't be mapped to more than one alias.</p>
Dries's avatar
Dries committed
30

31
32
33
<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
34

35
36
37
38
39
40
41
42
43
44
45
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
    return preg_replace('!^display/(\\d+)\$!', 'node/view/\\1', \$path);
  }
  else { // URL going out to a client
    \$aliased = preg_replace('!^node/view/(\\d+)\$!', 'display/\\1', \$path);
    if (\$aliased != \$path) { return \$aliased; }
  }
}
</pre>
<p>This function will shorten every <code>node/view/\$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>
<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/view/15</code> and <code>taxonomy/view/or/3</code>. You need extensive knowledge of Drupal's inner workings and regular expressions though to make such advanced aliases.</p>");
  }
}
Dries's avatar
   
Dries committed
52

53
54
55
56
57
58
59
60
61
62
63
64
/**
 * Implementation of hook_link().
 */
function path_link($type, $node = NULL) {
  if ($type == 'system') {
    menu('admin/path', t('url aliasing'), user_access('administer url aliases') ? 'path_admin' : MENU_DENIED, 4);
    menu('admin/path/add', t('new alias'), user_access('administer url aliases') ? 'path_admin_edit' : MENU_DENIED);
    menu('admin/path/edit', t('edit alias'), user_access('administer url aliases') ? 'path_admin_edit' : MENU_DENIED, 0, MENU_HIDE, MENU_LOCKED);
    menu('admin/path/delete', t('delete alias'), user_access('administer url aliases') ? 'path_admin_delete' : MENU_DENIED, 0, MENU_HIDE, MENU_LOCKED);
    menu('admin/path/help', t('help'), user_access('administer url aliases') ? 'path_admin_help' : MENU_DENIED, 9);
  }
}
Dries's avatar
   
Dries committed
65

66
67
68
69
70
71
72
73
74
75
76
77
78
/**
 * 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')) {
    $output = path_save($_POST['edit']);
Dries's avatar
Dries committed
79
  }
80
81
82
83
84
85
86
87
88
89
  else {
    if ($pid) {
      $output = path_form(path_load($pid));
    }
    else {
      $output = path_form();
    }
  }
  print theme('page', $output);
}
Dries's avatar
   
Dries committed
90

91
92
93
94
95
96
/**
 * Menu callback; handles deletion of an URL alias.
 */
function path_admin_delete($pid = 0) {
  path_delete($pid);
  print theme('page', path_overview());
Dries's avatar
Dries committed
97
98
}

99
100
101
102
103
104
105
106
107
108
/**
 * Menu callback; presents the path-specific information from admin/help.
 */
function path_admin_help() {
  print theme('page', path_help('admin/help#path'));
}

/**
 * Set an aliased path for a given Drupal path, preventing duplicates.
 */
Dries's avatar
   
Dries committed
109
110
function path_set_alias($path = NULL, $alias = NULL) {
  if ($path && !$alias) {
Dries's avatar
   
Dries committed
111
    db_query("DELETE FROM {url_alias} WHERE src = '%s'", $path);
Dries's avatar
   
Dries committed
112
113
114
    drupal_rebuild_path_map();
  }
  else if (!$path && $alias) {
Dries's avatar
   
Dries committed
115
    db_query("DELETE FROM {url_alias} WHERE dst = '%s'", $alias);
Dries's avatar
   
Dries committed
116
117
118
    drupal_rebuild_path_map();
  }
  else if ($path && $alias) {
Dries's avatar
   
Dries committed
119
120
    $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
121
122
123

    // We have an insert:
    if ($path_count == 0 && $alias_count == 0) {
124
      db_query("INSERT INTO {url_alias} (src, dst) VALUES ('%s', '%s')", $path, $alias);
Dries's avatar
   
Dries committed
125
126
127
      drupal_rebuild_path_map();
    }
    else if ($path_count == 1 && $alias_count == 0) {
Dries's avatar
   
Dries committed
128
      db_query("UPDATE {url_alias} SET dst = '%s' WHERE src = '%s'", $alias, $path);
Dries's avatar
   
Dries committed
129
130
131
      drupal_rebuild_path_map();
    }
    else if ($path_count == 0 && $alias_count == 1) {
Dries's avatar
   
Dries committed
132
      db_query("UPDATE {url_alias} SET src = '%s' WHERE dst = '%s'", $path, $alias);
Dries's avatar
   
Dries committed
133
134
135
136
137
138
139
140
141
      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
142
143
}

144
145
146
147
/**
 * Return a form for editing or creating an individual URL alias.
 */
function path_form($edit = '') {
Dries's avatar
Dries committed
148

149
150
  $form .= form_textfield(t('Existing path'), 'src', $edit['src'], 50, 64, t('Specify the existing path you wish to alias. For example: node/view/28, forum/1, taxonomy/page/or/1,2.'));
  $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
151

152
153
154
  if ($edit['pid']) {
    $form .= form_hidden('pid', $edit['pid']);
    $form .= form_submit(t('Update alias'));
Dries's avatar
   
Dries committed
155
156
  }
  else {
157
    $form .= form_submit(t('Create new alias'));
Dries's avatar
   
Dries committed
158
159
160
  }

  return form($form);
Dries's avatar
Dries committed
161
162
}

Dries's avatar
   
Dries committed
163
/**
164
165
166
167
 * 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
168
 */
Dries's avatar
   
Dries committed
169
function path_nodeapi(&$node, $op, $arg) {
170
  if (user_access('create url aliases') || user_access('administer url aliases')) {
Dries's avatar
Dries committed
171

Dries's avatar
   
Dries committed
172
    switch ($op) {
173
      case 'validate':
Dries's avatar
   
Dries committed
174
175
176
        // 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.
177
        if (is_null($node->path)) {
178
179
180
181
182
          $path = "node/view/$node->nid";
          $alias = drupal_get_path_alias($path);
          if ($alias != $path) {
            $node->path = $alias;
          }
Dries's avatar
   
Dries committed
183
184
        }
        else {
185
186
          $node->path = trim($node->path);
          if ($node->path && !valid_url($node->path)) {
187
            $error['path'] = t('The path is invalid.');
Dries's avatar
   
Dries committed
188
189
            return $error;
          }
Dries's avatar
   
Dries committed
190
          else if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE dst = '%s' AND src != '%s'", $node->path, "node/view/$node->nid"))) {
191
            $error['path'] = t('The path is already in use.');
Dries's avatar
   
Dries committed
192
193
194
195
            return $error;
          }
        }
        break;
Dries's avatar
Dries committed
196

197
198
      case 'form pre':
        return 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.') . theme_error($arg['path']));
Dries's avatar
   
Dries committed
199

200
201
202
      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
203
204
205
206
        if ($node->path) {
          path_set_alias("node/view/$node->nid", $node->path);
        }
        break;
207
      case 'update':
208
        path_set_alias("node/view/$node->nid", $node->path);
Dries's avatar
   
Dries committed
209
210
        break;

211
      case 'delete':
212
213
214
        $path = "node/view/$node->nid";
        if (drupal_get_path_alias($path) != $path) {
          path_set_alias($path);
Dries's avatar
   
Dries committed
215
216
217
        }
        break;
    }
Dries's avatar
Dries committed
218
219
220
  }
}

221
222
223
/**
 * Implementation of hook_perm().
 */
Dries's avatar
Dries committed
224
function path_perm() {
225
  return array('create url aliases', 'administer url aliases');
Dries's avatar
Dries committed
226
227
}

228
229
230
/**
 * Return a listing of all defined URL aliases.
 */
Dries's avatar
Dries committed
231
function path_overview() {
232
  $sql = 'SELECT * FROM {url_alias}';
Dries's avatar
Dries committed
233
  $header = array(
234
235
236
    array('data' => t('alias'), 'field' => 'dst', 'sort' => 'asc'),
    array('data' => t('normal'), 'field' => 'src'),
    array('data' => t('operations'), 'colspan' => 2)
Dries's avatar
Dries committed
237
238
239
240
241
  );
  $sql .= tablesort_sql($header);
  $result = pager_query($sql, 50);

  while ($data = db_fetch_object($result)) {
242
    $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
243
244
  }

245
246
  if ($pager = theme('pager', NULL, 50, 0, tablesort_pager())) {
    $rows[] = array(array('data' => $pager, 'colspan' => '4'));
Dries's avatar
Dries committed
247
248
  }

Dries's avatar
   
Dries committed
249
  if (!$rows) {
250
    $rows[] = array(array('data' => t('No URL aliases available.'), 'colspan' => '4'));
Dries's avatar
   
Dries committed
251
252
  }

253
  return theme('table', $header, $rows);
Dries's avatar
Dries committed
254
255
}

256
257
258
/**
 * Fetch a specific URL alias from the database.
 */
Dries's avatar
   
Dries committed
259
function path_load($pid) {
260
  return db_fetch_array(db_query('SELECT * FROM {url_alias} WHERE pid = %d', $pid));
Dries's avatar
   
Dries committed
261
}
Dries's avatar
Dries committed
262

263
264
265
/**
 * Remove an URL alias from the database.
 */
Dries's avatar
   
Dries committed
266
function path_delete($pid) {
267
268
  db_query('DELETE FROM {url_alias} WHERE pid = %d', $pid);
  drupal_set_message(t('the alias has been deleted.'));
Dries's avatar
   
Dries committed
269
}
Dries's avatar
Dries committed
270

271
272
273
/**
 * Verify that a new URL alias is valid, and save it to the database.
 */
Dries's avatar
   
Dries committed
274
function path_save($edit) {
275
276
277
  $src = $edit['src'];
  $dst = $edit['dst'];
  $pid = $edit['pid'];
Dries's avatar
Dries committed
278

Dries's avatar
   
Dries committed
279
  if (!valid_url($src)) {
Dries's avatar
   
Dries committed
280
    form_set_error('src', t('the normal path "%src" is invalid.', array('%src' => $src)));
Dries's avatar
Dries committed
281
282
  }

283
  if (db_result(db_query("SELECT COUNT(src) FROM {url_alias} WHERE pid != %d AND src = '%s'", $pid, $src))) {
Dries's avatar
   
Dries committed
284
    form_set_error('src', t('the normal path "%src" is already aliased.', array('%src' => $src)));
Dries's avatar
Dries committed
285
286
  }

Dries's avatar
   
Dries committed
287
  if (!valid_url($dst)) {
Dries's avatar
   
Dries committed
288
    form_set_error('dst', t('the alias "%dst" is invalid.', array('%dst' => $dst)));
Dries's avatar
Dries committed
289
290
  }

291
  if (db_result(db_query("SELECT COUNT(dst) FROM {url_alias} WHERE pid != %d AND dst = '%s'", $pid, $dst))) {
Dries's avatar
   
Dries committed
292
    form_set_error('dst', t('the alias "%dst" is already in use.', array('%dst' => $dst)));
Dries's avatar
   
Dries committed
293
  }
Dries's avatar
Dries committed
294

Dries's avatar
   
Dries committed
295
  if (form_has_errors()) {
Dries's avatar
   
Dries committed
296
    return path_form($edit, $error);
Dries's avatar
Dries committed
297
  }
Dries's avatar
   
Dries committed
298
  else {
299
300
301
    // Normally, you would use path_set_alias() to update the paths table,
    // but this is a special case.  We want to modify a specific row and the only
    // way to do that is with pid.
Dries's avatar
   
Dries committed
302
303

    if ($pid) {
304
      db_query("UPDATE {url_alias} SET src = '%s', dst = '%s' WHERE pid = %d", $src, $dst, $pid);
Dries's avatar
   
Dries committed
305
306
307
308
    }
    else {
      path_set_alias($src, $dst);
    }
Dries's avatar
Dries committed
309

Dries's avatar
   
Dries committed
310
    drupal_set_message(t('the alias has been saved.'));
Dries's avatar
   
Dries committed
311

Dries's avatar
   
Dries committed
312
313
    return  path_overview();
  }
Dries's avatar
Dries committed
314
315
316
}

?>