link.module 11.3 KB
Newer Older
Nathan Haug's avatar
Nathan Haug committed
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
<?php
// $Id$

/**
 * @file
 * Defines simple link field types.
 */

/**
 * Implementation of hook_help().
 */
function link_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Defines simple link field types. <em>Note: Requires content.module.</em>');
  }
}

/**
 * Implementation of hook_field_info().
 */
function link_field_info() {
  return array(
    'link' => array('label' => 'Link'),
  );
}

/**
 * Implementation of hook_field_settings().
 */
function link_field_settings($op, $field) {
  switch ($op) {
    case 'form':
      $form = array();
35
36
37
38
39
40
41
42
43
44
45
46
47
48
      
      $options = array (
        'optional' => t('Optional Title'),
        'required' => t('Required Title'),
        'none' => t('No Title'),
      );
      
      $form['title'] = array(
        '#type' => 'radios',
        '#title' => t('Link Title'),
        '#default_value' => isset($field['title']) ? $field['title'] : 'optional',
        '#options' => $options,
      );
      
Nathan Haug's avatar
Nathan Haug committed
49
50
51
52
53
54
55
      $options = array(
        'default' => t('Default (no target attribute)'),
        '_top' => t('Open link in window root'),
        '_blank' => t('Open link in new window'),
        'user' => t('Allow the user to choose'),
      );
      $form['attributes'] = array (
56
        '#tree' => true,
Nathan Haug's avatar
Nathan Haug committed
57
58
59
60
61
62
63
      );
      $form['attributes']['target'] = array(
        '#type' => 'radios',
        '#title' => t('Link Target'),
        '#default_value' => $field['attributes']['target'] ? $field['attributes']['target'] : 'default',
        '#options' => $options,
      );
Nathan Haug's avatar
Nathan Haug committed
64
65
66
67
68
69
70
71
72
      $form['attributes']['rel'] = array(
        '#type' => 'checkbox',
        '#return_value' => 'nofollow',
        '#prefix' => '<div class="form-item"><label>Nofollow Value: </label>',
        '#suffix' => '</div>',
        '#title' => t('Add rel=&quot;nofollow&quot; Attribute'),
        '#description' => t('The <a href="http://en.wikipedia.org/wiki/Nofollow#rel.3Dnofollow">rel=&quot;nofollow&quot; attribute</a> prevents some search engines from spidering entered links.'),
        '#default_value' => isset($field['attributes']['rel']) ? $field['attributes']['rel'] : false,
      );
Nathan Haug's avatar
Nathan Haug committed
73
74
75
      return $form;

    case 'save':
76
      return array('attributes', 'title');
77
78
79
80
81
82

    case 'database columns':
      return array(
        'url' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => "''"),
        'title' => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => "''"),
        'attributes' => array('type' => 'mediumtext', 'not null' => TRUE, 'default' => "''"),
83
      );
84
85
86

    case 'filters':
      return array(
87
88
89
90
91
        'default' => array(
          'operator' => 'views_handler_operator_like',
          'handler' => 'views_handler_filter_like',
        ),
      );
92

Nathan Haug's avatar
Nathan Haug committed
93
94
95
96
97
98
  }
}

/**
 * Implementation of hook_field().
 */
99
function link_field($op, &$node, $field, &$items, $teaser, $page) {
Nathan Haug's avatar
Nathan Haug committed
100
101
102
  switch ($op) {

    case 'view':
103
104
      foreach ($items as $delta => $item) {
        $items[$delta]['view'] = content_format($field, $item, 'default', $node);
Nathan Haug's avatar
Nathan Haug committed
105
      }
106
107
      return theme('field', $node, $field, $items, $teaser, $page);
    break;
Nathan Haug's avatar
Nathan Haug committed
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
  }
}

/**
 * Implementation of hook_widget_info().
 */
function link_widget_info() {
  return array(
    'link' => array(
      'label' => 'Text Fields for Title and URL',
      'field types' => array('link'),
    ),
  );
}

/**
 * Implementation of hook_widget().
 */
function link_widget($op, &$node, $field, &$node_field) {
  switch ($op) {
    case 'form':
      $form = array();

      $form[$field['field_name']] = array('#tree' => TRUE);

      if ($field['multiple']) {
134
135
136
137
        // Generate more fields if necessary on preview
        if ($_POST['edit'][$field['field_name']]) {
          $node_field = $_POST['edit'][$field['field_name']];
        }
Nathan Haug's avatar
Nathan Haug committed
138
        $delta = 0;
139
        // Render link fields for all the entered values
Nathan Haug's avatar
Nathan Haug committed
140
        foreach ($node_field as $data) {
141
        if ($data['url']) {
142
            _link_widget_form($form[$field['field_name']][$delta], $field, $data, $delta);
Nathan Haug's avatar
Nathan Haug committed
143
144
145
            $delta++;
          }
        }
146
        // Render two additional new link fields
Nathan Haug's avatar
Nathan Haug committed
147
        foreach (range($delta, $delta + 1) as $delta) {
148
          _link_widget_form($form[$field['field_name']][$delta], $field, $node_field, $delta);
Nathan Haug's avatar
Nathan Haug committed
149
150
151
        }
      } // end if multiple
      else {
Nathan Haug's avatar
Nathan Haug committed
152
        _link_widget_form($form[$field['field_name']][0], $field, $node_field[0]);
Nathan Haug's avatar
Nathan Haug committed
153
154
155
156
      }
      return $form;

    case 'validate':
Nathan Haug's avatar
Nathan Haug committed
157
      foreach($node_field as $delta => $value) {
158
        if ($value['url']) {
Nathan Haug's avatar
Nathan Haug committed
159
          // Validate the link
160
161
          if (link_validate_url(trim($value['url'])) == FALSE) {
            form_set_error($field['field_name'] .']['. $delta. '][url', t('Not a valid URL.'));
162
          }
Nathan Haug's avatar
Nathan Haug committed
163
          // Require a title for the link if necessary
164
          elseif ($field['title'] == 'required' && strlen(trim($value['title'])) == 0) {
165
            form_set_error($field['field_name'] .']['. $delta. '][title', t('Titles are required for all links.'));
Nathan Haug's avatar
Nathan Haug committed
166
167
          }
        }
Nathan Haug's avatar
Nathan Haug committed
168
        // Require a link if we have a title
169
        elseif (strlen($value['title']) > 0) {
170
          form_set_error($field['field_name'] .']['. $delta. '][link', t('You cannot enter a title without a link.'));
171
        }
Nathan Haug's avatar
Nathan Haug committed
172
173
174
175
      }
      return;
      
    case 'process form values':
Nathan Haug's avatar
Nathan Haug committed
176
177
      foreach($node_field as $delta => $value) {
        _link_widget_process($node_field[$delta],$delta);
Nathan Haug's avatar
Nathan Haug committed
178
179
180
181
182
183
184
185
      }
      return;
    
    case 'submit':
      return;
  }
}

186
187
188
189
190
/**
 * Helper function renders the link widget in both single and multiple value cases.
 */

function _link_widget_form (&$form_item, $field, $node_field, $delta = 0) {
191
192
  
  $form_item = array(
193
    '#tree' => true,
194
195
    // Add a microweight to keep fields in first-in first-out order
    '#weight' => $field['widget']['weight'].".00".$delta,
196
  );
197
  $form_item['url'] = array(
198
    '#type' => 'textfield',
Nathan Haug's avatar
Nathan Haug committed
199
200
    '#maxlength' => '255',
    '#title' => $field['title'] == 'none' ? t($field['widget']['label']) : t($field['widget']['label'])." ".t('URL'),
201
    '#default_value' => $node_field['url'],
202
    '#required' => ($delta == 0) ? $field['required'] : FALSE,
Nathan Haug's avatar
Nathan Haug committed
203
    '#description' => $field['widget']['description'],
204
  );
205
  if ($field['title'] != 'none') {
206
    $form_item['title'] = array(
207
      '#type' => 'textfield',
Nathan Haug's avatar
Nathan Haug committed
208
      '#maxlength' => '255',
209
      '#title' => t($field['widget']['label'])." ".t('Title'),
210
      '#default_value' => $node_field['title'],
211
212
213
      '#required' => ($delta == 0 && $field['title'] == 'required') ? $field['required'] : FALSE,
    );
  }
214
  if ($field['attributes']['target'] == 'user') {
215
    $form_item['attributes']['target'] = array(
216
217
      '#type' => 'checkbox',
      '#title' => t('Open URL in a New Window'),
218
      '#default_value' => $node_field['attributes']['target'],
219
220
221
222
223
      '#return_value' => "_blank",
    );
  }
}

224
225
function _link_widget_process (&$node_field, $delta = 0) {
  // Remove the target attribute if not selected
226
227
  if (!$node_field['attributes']['target'] || $node_field['attributes']['target'] == "default") {
    unset($node_field['attributes']['target']);
Nathan Haug's avatar
Nathan Haug committed
228
  }
229
230
  // Trim whitespace from URL
  $node_field['url'] = trim($node_field['url']);
231
232
}

Nathan Haug's avatar
Nathan Haug committed
233
/**
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
 * Implementation of hook_field_formatter_info().
 */
function link_field_formatter_info() {
  return array(
    'default' => array(
      'label' => 'Default, as link',
      'field types' => array('link'),
    ),
    'plain' => array(
      'label' => 'Plain, no link',
      'field types' => array('link'),
    ),
  );
}

/**
 * Implementation of hook_field_formatter().
 *
Nathan Haug's avatar
Nathan Haug committed
252
 */
253
function link_field_formatter($field, $item, $formatter) {
254
255
256
  if (empty($item['url'])) {
    return '';
  }
257
258
259
260
261
  
  if ($formatter == 'plain') {
    return check_plain($item['url']);
  }
  
262
  $attributes = array();
Nathan Haug's avatar
Nathan Haug committed
263
  // Add attributes defined at the widget level
264
265
266
  if (is_array($item['attributes'])) {
    foreach($item['attributes'] as $attribute => $attbvalue) {
      if (isset($item['attributes'][$attribute]) && $field['attributes'][$attribute] == 'user') {
267
268
        $attributes[$attribute] = $attbvalue;
      }
Nathan Haug's avatar
Nathan Haug committed
269
270
271
272
273
274
    }
  }
  // Add attributes defined at the field level
  if (is_array($field['attributes'])) {
    foreach($field['attributes'] as $attribute => $attbvalue) {
      if (!empty($attbvalue) && $attbvalue != 'default' && $attbvalue != 'user') {
275
        $attributes[$attribute] = $attbvalue;
Nathan Haug's avatar
Nathan Haug committed
276
277
278
      }
    }
  }
279
280
281
282
283
284
285
286
287
288
289
290
  
  $url = link_cleanup_url($item['url']);
      
  if (strpos($url, '#') !== FALSE) {
    $fragment = substr($url, strpos($url, '#') + 1);
    $url = substr($url, 0, strpos($url, '#'));
  }
  if (strpos($url, '?') !== FALSE) {
    $query = substr($url, strpos($url, '?') + 1);
    $url = substr($url, 0, strpos($url, '?'));
  }
  
Nathan Haug's avatar
Nathan Haug committed
291
  // Build the link with a title
292
  if (strlen(trim($item['title']))) {
293
    $output = l($item['title'], $url, $attributes, $query, $fragment);
Nathan Haug's avatar
Nathan Haug committed
294
  }
295
  // Build the link with the URL as the title (max 80 characters)
Nathan Haug's avatar
Nathan Haug committed
296
  else {
297
298
    $display_url = url($url, $query, $fragment, TRUE);
    $output = l(strlen($display_url) > 80 ? substr($display_url,0,80)."..." : $display_url, $url, $attributes, $query, $fragment);
Nathan Haug's avatar
Nathan Haug committed
299
300
301
302
  }
  return $output;
}

303
304
305
306
/**
 * Forms a valid URL if possible from an entered address.
 * Trims whitespace and automatically adds an http:// to addresses without a protocol specified
 *
307
308
 * @param string $url
 * @param string $protocol The protocol to be prepended to the url if one is not specified
309
 */
310
function link_cleanup_url ($url, $protocol = "http") {
311
  $url = trim($url);
312
313
314
315
316
317
318
319
320
321
  $type = link_validate_url($url);
  if ($type == 1) {
    // Check if there is no protocol specified
    $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i",$url);
    if (empty($protocol_match)) {
      // But should it be? Add an automatic http:// if it starts with a domain name
      $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|[a-z]{2}))/i',$url);
      if (!empty($domain_match)) {
        $url = $protocol."://".$url;
      }
322
323
324
    }
  }
  
325
  return $url;
326
327
328
329
330
331
332
333
334
}

/**
 * A lenient verification for URLs. Accepts all URLs following RFC 1738 standard for URL formation.  
 *
 * @param string $text
 * @return mixed Returns boolean FALSE if the URL is not valid. On success, returns an object with
 * the following attributes: protocol, hostname, ip, and port.
 */
335
336
337
338
339
340
341
342
function link_validate_url($text) {
  static $allowed_protocols;
  if (!isset($allowed_protocols)) {
    $allowed_protocols = implode("|",variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal')));
  } 
  
  $external_pattern = 
  // protocol
343
  '/^((' . $allowed_protocols . '):\/\/)?'.
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
  '('.
    // domains
    '(([a-z0-9]([a-z0-9\-_]*\.)+)(aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|[a-z]{2}))'.
    // OR ip addresses
    '|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'.
  ')'.
  // port number
  '(:([0-9]{1,4}))?';
  
  // Starting path
  $internal_pattern = "/^([a-z0-9_\-+]+)";
  
  // the rest of the path
  $end = "(\/[a-z0-9_\-\.~+%=&,$'():;*@]+)*".
  // forward slash 0 or 1 times
  '(\/)?'.
  // query string
  "(\/?\?[a-z0-9+_\-\.\/%=&,$'():;*@]*)?".
  // anchors
  "(#[a-z0-9_\-\.~+%=&,$'():;*@]*)?".
  // end of the expression, case insensitive
  '$/i';
  
  if (preg_match($external_pattern . $end, $text, $m)) {
    return 1;
Nathan Haug's avatar
Nathan Haug committed
369
  }
370
371
372
373
374
  elseif (preg_match($internal_pattern . $end, $text, $m)) {
    return 2;
  }
  elseif (strpos($text, '<front>') === 0) {
    return 3;
Nathan Haug's avatar
Nathan Haug committed
375
  }
376
  return FALSE;
377
}