link.module 10.5 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
83
84
85
86
87
88
89
90
91
92

    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' => "''"),
        );

    case 'filters':
      return array(
          'default' => array(
            'operator' => 'views_handler_operator_like',
            'handler' => 'views_handler_filter_like',
          ),
        );

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_link($value['url'])) {
            form_set_error($field['field_name'] .']['. $delta. '][value][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) {
Nathan Haug's avatar
Nathan Haug committed
165
            form_set_error($field['field_name'] .']['. $delta. '][value][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) {
Nathan Haug's avatar
Nathan Haug committed
170
          form_set_error($field['field_name'] .']['. $delta. '][value][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
}

Nathan Haug's avatar
Nathan Haug committed
231
/**
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
 * 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
250
 */
251
252
253
254
255
256
function link_field_formatter($field, $item, $formatter) {
  
  if ($formatter == 'plain') {
    return check_plain($item['url']);
  }
  
257
  $attributes = array();
Nathan Haug's avatar
Nathan Haug committed
258
  // Add attributes defined at the widget level
259
260
261
  if (is_array($item['attributes'])) {
    foreach($item['attributes'] as $attribute => $attbvalue) {
      if (isset($item['attributes'][$attribute]) && $field['attributes'][$attribute] == 'user') {
262
263
        $attributes[$attribute] = $attbvalue;
      }
Nathan Haug's avatar
Nathan Haug committed
264
265
266
267
268
269
    }
  }
  // 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') {
270
        $attributes[$attribute] = $attbvalue;
Nathan Haug's avatar
Nathan Haug committed
271
272
273
274
      }
    }
  }
  // Build the link with a title
275
276
  if (strlen(trim($item['title']))) {
    $output = l($item['title'],link_cleanup_url($item['url']),$attributes);
Nathan Haug's avatar
Nathan Haug committed
277
  }
278
  // Build the link with the URL as the title (max 80 characters)
Nathan Haug's avatar
Nathan Haug committed
279
  else {
280
    $output = l(strlen($item['url']) > 80 ? substr($item['url'],0,80)."..." : $item['url'],link_cleanup_url($item['url']),$attributes);
Nathan Haug's avatar
Nathan Haug committed
281
282
283
284
  }
  return $output;
}

285
286
287
288
/**
 * Forms a valid URL if possible from an entered address.
 * Trims whitespace and automatically adds an http:// to addresses without a protocol specified
 *
289
290
 * @param string $url
 * @param string $protocol The protocol to be prepended to the url if one is not specified
291
 */
292
function link_cleanup_url ($url, $protocol = "http") {
293
294
295
296
297
298
299
300
  $url = trim($url);
  
  // 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)) {
301
      $url = $protocol."://".$url;
302
303
304
    }
  }
  
305
  return check_url($url);
306
307
308
309
310
311
312
313
314
}

/**
 * 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.
 */
Nathan Haug's avatar
Nathan Haug committed
315
function link_validate_link($text) {
316
  if (!preg_match(
317
318
    // protocol
    '/^([a-z0-9][a-z0-9\.\-_]*:\/\/)?'.
319
320
  '('.
    // domains
321
      '(([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}))'.
Nathan Haug's avatar
Nathan Haug committed
322
323
      // OR ip addresses
      '|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'.
324
  ')'.
Nathan Haug's avatar
Nathan Haug committed
325
326
    // port number
    '(:([0-9]{1,4}))?'.
Nathan Haug's avatar
Nathan Haug committed
327
328
329
    // the rest of the path
    "(\/[a-z0-9_\-\.~+%=&,$'():;*@]+)*".
    // anchors
Nathan Haug's avatar
Nathan Haug committed
330
    "\/?#?[a-z0-9_\-\.~+%=&,$'():;*@]*".
Nathan Haug's avatar
Nathan Haug committed
331
    // the query string
Nathan Haug's avatar
Nathan Haug committed
332
    "(\/?\?[a-z0-9+_\-\.\/%=&,$'():;*@]*)?".
Nathan Haug's avatar
Nathan Haug committed
333
334
335
336
    // forward slash 0 or 1 times
    '(\/)?'.
    // end of the expression, case insensitive
    '$/i', $text, $m)) {
337
    return false;
Nathan Haug's avatar
Nathan Haug committed
338
339
  }
  else {
340
    $url = new stdClass();
Nathan Haug's avatar
Nathan Haug committed
341
342
343
344
345
346
    $url->protocol = $m[2];
    $url->hostname = strtolower($m[5]).strtolower($m[7]);
    $url->ip = $m[8];
    $url->port = $m[10];
    return $url;
  }
347
}