link.module 14.6 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');
Nathan Haug's avatar
Nathan Haug committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
  }
}

/**
 * Implementation of hook_field().
 */
function link_field($op, &$node, $field, &$node_field, $teaser, $page) {
  switch ($op) {
    case 'load':
      switch($field['type']) {
        case 'link':
          $result = db_query("SELECT field_url, field_title, attributes FROM {node_field_link_data} WHERE vid = %d AND field_name = '%s' ORDER BY delta", $node->vid, $field['field_name']);
          if ($field['multiple']) {
            $values = array();
            while ($value = db_fetch_array($result)) {
              $values[] = array('value' => array('link' => $value['field_url'], 'title' => $value['field_title'], 'attributes' => unserialize($value['attributes'])));
            }
            $additions = array($field['field_name'] => $values);
          }
          else {
            $dbvalue = db_fetch_array($result);
            $value = array ('link' => $dbvalue['field_url'], 'title' => $dbvalue['field_title'], 'attributes' => unserialize($dbvalue['attributes']));
            $additions = array($field['field_name'] => array('value' => $value));
          }
          break;
      }
      return $additions;

    case 'view':
      $output = '';
      if ($field['multiple']) {
108
109
110
111
112
        // Convert an old 'single value' field to the first of multiple
        if ($node_field['value']) {
          $node_field[0]['value'] = $node_field['value'];
          unset($node_field['value']);
        }
Nathan Haug's avatar
Nathan Haug committed
113
        foreach ($node_field as $delta => $item) {
114
          $node_field[$delta]['view'] = _link_field_view($field, $item['value'], $item, $node);
Nathan Haug's avatar
Nathan Haug committed
115
116
117
        }
      }
      else {
118
119
120
121
122
123
        // Convert an old 'multiple value' field to single
        if ($node_field[0]['value']) {
          $node_field['value'] = $node_field[0]['value'];
          unset($node_field[0]['value']);
        }
        $node_field['view'] = _link_field_view($field, $node_field['value'], $node_field, $node);
Nathan Haug's avatar
Nathan Haug committed
124
      }
125
      
Nathan Haug's avatar
Nathan Haug committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
      $node->$field['field_name'] = $node_field;
      if ($field['multiple']) {
        $output = '';
        foreach ($node_field as $delta => $item) {
          $output .= '<div class="'. $field['field_name'] .'">'. $item['view'] .'</div>';
        }
        return $output;
      }
      else {
        return '<div class="'. $field['field_name'] .'">'. $node_field['view'] .'</div>';
      }

    case 'insert':
      switch($field['type']) {
        case 'link':
          if ($field['multiple']) {
            foreach ($node_field as $delta => $item) {
              if ($item['value']['link']) {
                db_query("INSERT INTO {node_field_link_data} (nid, vid, field_name, delta, field_url, field_title, attributes) VALUES (%d, %d, '%s', %d, '%s', '%s', '%s')", $node->nid, $node->vid, $field['field_name'], $delta, $item['value']['link'], $item['value']['title'], serialize($item['value']['attributes']));
              }
            }
          }
          else {
            if ($node_field['value']['link']) {
              db_query("INSERT INTO {node_field_link_data} (nid, vid, field_name, field_url, field_title, attributes) VALUES (%d, %d, '%s', '%s', '%s', '%s')", $node->nid, $node->vid, $field['field_name'], $node_field['value']['link'], $node_field['value']['title'], serialize($node_field['value']['attributes']));
            }
          }
          break;
      }
      return;

    case 'update':
      // Delete and insert, rather than update, in case a field was added.
      switch($field['type']) {
        case 'link':
          link_field('delete', $node, $field, $node_field, $teaser, $page);
          link_field('insert', $node, $field, $node_field, $teaser, $page);
          break;
      }
      return;

    case 'delete':
      // Delete using nid rather than vid to purge all revisions.
      switch($field['type']) {
        case 'link':
          db_query("DELETE FROM {node_field_link_data} WHERE nid = %d AND field_name = '%s'", $node->nid, $field['field_name']);
          break;
      }
      return;
  }
}

/**
 * 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']) {
201
202
203
204
205
206
207
208
209
        // Generate more fields if necessary on preview
        if ($_POST['edit'][$field['field_name']]) {
          $node_field = $_POST['edit'][$field['field_name']];
        }
        // Convert an old 'single' value field into the first value of a new multi-value field
        if ($node_field['value']) {
          $node_field[0]['value'] = $node_field['value'];
          unset($node_field['value']);
        }
Nathan Haug's avatar
Nathan Haug committed
210
        $delta = 0;
211
        // Render link fields for all the entered values
Nathan Haug's avatar
Nathan Haug committed
212
        foreach ($node_field as $data) {
213
214
        if ($data['value']['link']) {
            _link_widget_form($form[$field['field_name']][$delta], $field, $data, $delta);
Nathan Haug's avatar
Nathan Haug committed
215
216
217
            $delta++;
          }
        }
218
        // Render two additional new link fields
Nathan Haug's avatar
Nathan Haug committed
219
        foreach (range($delta, $delta + 1) as $delta) {
220
          _link_widget_form($form[$field['field_name']][$delta], $field, $node_field, $delta);
Nathan Haug's avatar
Nathan Haug committed
221
222
223
        }
      } // end if multiple
      else {
224
225
226
227
228
229
        // Convert an old 'multiple' value field into the value of a new single-value field
        if ($node_field[0]['value']) {
          $node_field['value'] = $node_field[0]['value'];
          unset($node_field[0]['value']);
        }
        _link_widget_form($form[$field['field_name']], $field, $node_field);
Nathan Haug's avatar
Nathan Haug committed
230
231
232
233
234
235
      }
      return $form;

    case 'validate':
      if ($field['multiple']) {
        foreach($node_field as $delta => $value) {
236
          if ($node_field[$delta]['value']['link']) {
237
            // Validate the link
238
            if (!link_validate_link($value['value']['link'])) {
Nathan Haug's avatar
Nathan Haug committed
239
240
              form_set_error($field['field_name'] .']['. $delta. '][value][link', t('Not a valid URL.'));
            }
241
242
243
244
245
246
247
248
            // Require a title for the link if necessary
            elseif ($field['title'] == 'required' && strlen(trim($value['value']['title'])) == 0) {
              form_set_error($field['field_name'] .']['. $delta. '][value][title', t('Titles are required for all links.'));
            }
          }
          // Require a link if we have a title
          elseif (strlen($value['value']['title']) > 0) {
            form_set_error($field['field_name'] .']['. $delta. '][value][link', t('You cannot enter a title without a link.'));
Nathan Haug's avatar
Nathan Haug committed
249
250
251
252
          }
        }
      }
      else {
253
        if ($node_field['value']['link']) {
Nathan Haug's avatar
Nathan Haug committed
254
255
256
          if (!link_validate_link($node_field['value']['link'])) {
            form_set_error($field['field_name'] .'][value][link', t('Not a valid URL.'));
          }
257
        }
Nathan Haug's avatar
Nathan Haug committed
258
259
260
261
262
263
      }
      return;
      
    case 'process form values':
      if ($field['multiple']) {
        foreach($node_field as $delta => $value) {
264
           if (!$node_field[$delta]['value']['attributes']['target'] || $node_field[$delta]['value']['attributes']['target'] == "default") {
Nathan Haug's avatar
Nathan Haug committed
265
266
267
268
269
            unset($node_field[$delta]['value']['attributes']['target']);
          }
        }
      }
      else {
270
         if (!$node_field['value']['attributes']['target'] || $node_field[$delta]['value']['attributes']['target'] == "default") {
Nathan Haug's avatar
Nathan Haug committed
271
272
273
274
275
276
277
278
279
280
          unset($node_field['value']['attributes']['target']);
        }
      }
      return;
    
    case 'submit':
      return;
  }
}

281
282
283
284
285
286
287
288
289
290
291
292
293
294
/**
 * Helper function renders the link widget in both single and multiple value cases.
 */

function _link_widget_form (&$form_item, $field, $node_field, $delta = 0) {
  $form_item['value'] = array(
    '#tree' => true,
  );
  $form_item['value']['link'] = array(
    '#type' => 'textfield',
    '#title' => t($field['widget']['label'])." ".t('URL'),
    '#default_value' => $node_field['value']['link'],
    '#required' => ($delta == 0) ? $field['required'] : FALSE,
  );
295
296
297
298
299
300
301
302
  if ($field['title'] != 'none') {
    $form_item['value']['title'] = array(
      '#type' => 'textfield',
      '#title' => t($field['widget']['label'])." ".t('Title'),
      '#default_value' => $node_field['value']['title'],
      '#required' => ($delta == 0 && $field['title'] == 'required') ? $field['required'] : FALSE,
    );
  }
303
304
305
306
307
308
309
310
311
312
  if ($field['attributes']['target'] == 'user') {
    $form_item['value']['attributes']['target'] = array(
      '#type' => 'checkbox',
      '#title' => t('Open URL in a New Window'),
      '#default_value' => $node_field['value']['attributes']['target'],
      '#return_value' => "_blank",
    );
  }
}

Nathan Haug's avatar
Nathan Haug committed
313
314
315
/**
 * Implementation of hook_field_view() which performs any translation necessary.
 */
316
317
function _link_field_view($field, $value, $addlfields = array(), $node = NULL) {
  $attributes = array();
Nathan Haug's avatar
Nathan Haug committed
318
319
320
  // Add attributes defined at the widget level
  if (is_array($value['attributes'])) {
    foreach($value['attributes'] as $attribute => $attbvalue) {
321
322
323
      if (isset($field['attributes'][$attribute]) && $field['attributes'][$attribute] == 'user') {
        $attributes[$attribute] = $attbvalue;
      }
Nathan Haug's avatar
Nathan Haug committed
324
325
326
327
328
329
    }
  }
  // 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') {
330
        $attributes[$attribute] = $attbvalue;
Nathan Haug's avatar
Nathan Haug committed
331
332
333
334
335
      }
    }
  }
  // Build the link with a title
  if (strlen(trim($value['title']))) {
336
    $output = l($value['title'],$value['link'],$attributes);
Nathan Haug's avatar
Nathan Haug committed
337
  }
338
  // Build the link with the URL as the title (max 80 characters)
Nathan Haug's avatar
Nathan Haug committed
339
  else {
340
    $output = l(strlen($value['link']) > 80 ? substr($value['link'],0,80)."..." : $value['link'],$value['link'],$attributes);
Nathan Haug's avatar
Nathan Haug committed
341
342
343
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
  }
  return $output;
}

/**
 * Implementation of hook_views_tables().
 */
function link_views_tables() {
  $tables = array();

  $fields = content_fields();
  foreach ($fields as $field) {
    if ($field['type'] == 'link') {
      $tables['node_field_link_data_'. $field['field_name']] = array(
        'name' => 'node_field_link_data',
        'join' => array(
          'left' => array(
            'table' => 'node',
            'field' => 'vid',
          ),
          'right' => array(
            'field' => 'vid',
          ),
            'extra' => array('field_name' => $field['field_name']),
        ),
        'fields' => array(
          'field_url' => array(
            'name' => 'Link URL: '. $field['field_name'],
            'sortable' => TRUE,
          ),
          'field_title' => array(
            'name' => 'Link Title: '. $field['field_name'],
            'sortable' => TRUE,
          ),
        ),
        'sorts' => array(
          'field_url' => array('name' => 'Link URL: '. $field['field_name']),
          'field_title' => array('name' => 'Link Title: '. $field['field_name']),
        ),
        'filters' => array(
          'field_url' => array(
            'name' => 'Link URL: '. $field['field_name'],
            'operator' => array(
              '='  => 'is',
              'contains' => 'contains',
              'begins' => 'begins with',
              'ends' => 'ends wth',
              'LIKE'  => 'matches pattern',
            ),
            'operator-handler' => '_text_filter_operator',
          ),
          'field_title' => array(
            'name' => 'Link Title: '. $field['field_name'],
            'operator' => array(
              '='  => 'is',
              'contains' => 'contains',
              'begins' => 'begins with',
              'ends' => 'ends wth',
              'LIKE'  => 'matches pattern',
            ),
            'operator-handler' => '_text_filter_operator',
          ),
        ),
      );
    }
  }

  return $tables;
}

function link_validate_link($text) {
412
413
  if (!preg_match(
    // The protocols: http://
Nathan Haug's avatar
Nathan Haug committed
414
    '/^((https|http|ftp|news):\/\/)?'.
415
416
  '('.
    // domains
Nathan Haug's avatar
Nathan Haug committed
417
418
419
      '(([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}))'.
      // OR ip addresses
      '|(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'.
420
  ')'.
Nathan Haug's avatar
Nathan Haug committed
421
422
    // port number
    '(:([0-9]{1,4}))?'.
423
  // the rest of the path
424
  '(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.\/%=&,:]*)?)?'.
Nathan Haug's avatar
Nathan Haug committed
425
426
427
428
    // forward slash 0 or 1 times
    '(\/)?'.
    // end of the expression, case insensitive
    '$/i', $text, $m)) {
429
    return false;
Nathan Haug's avatar
Nathan Haug committed
430
431
  }
  else {
432
    $url = new stdClass();
Nathan Haug's avatar
Nathan Haug committed
433
434
435
436
437
438
    $url->protocol = $m[2];
    $url->hostname = strtolower($m[5]).strtolower($m[7]);
    $url->ip = $m[8];
    $url->port = $m[10];
    return $url;
  }
439
}