link.module 13.9 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
64
65
66
      );
      $form['attributes']['target'] = array(
        '#type' => 'radios',
        '#title' => t('Link Target'),
        '#default_value' => $field['attributes']['target'] ? $field['attributes']['target'] : 'default',
        '#options' => $options,
      );
      return $form;

    case 'save':
67
      return array('attributes', 'title');
Nathan Haug's avatar
Nathan Haug committed
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
  }
}

/**
 * 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']) {
99
100
101
102
103
        // 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
104
        foreach ($node_field as $delta => $item) {
105
          $node_field[$delta]['view'] = _link_field_view($field, $item['value'], $item, $node);
Nathan Haug's avatar
Nathan Haug committed
106
107
108
        }
      }
      else {
109
110
111
112
113
114
        // 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
115
      }
116
      
Nathan Haug's avatar
Nathan Haug committed
117
118
119
120
121
122
123
124
125
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
      $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']) {
192
193
194
195
196
197
198
199
200
        // 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
201
        $delta = 0;
202
        // Render link fields for all the entered values
Nathan Haug's avatar
Nathan Haug committed
203
        foreach ($node_field as $data) {
204
205
        if ($data['value']['link']) {
            _link_widget_form($form[$field['field_name']][$delta], $field, $data, $delta);
Nathan Haug's avatar
Nathan Haug committed
206
207
208
            $delta++;
          }
        }
209
        // Render two additional new link fields
Nathan Haug's avatar
Nathan Haug committed
210
        foreach (range($delta, $delta + 1) as $delta) {
211
          _link_widget_form($form[$field['field_name']][$delta], $field, $node_field, $delta);
Nathan Haug's avatar
Nathan Haug committed
212
213
214
        }
      } // end if multiple
      else {
215
216
217
218
219
220
        // 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
221
222
223
224
225
226
      }
      return $form;

    case 'validate':
      if ($field['multiple']) {
        foreach($node_field as $delta => $value) {
227
          if ($node_field[$delta]['value']['link']) {
228
            // Validate the link
229
            if (!link_validate_link($value['value']['link'])) {
Nathan Haug's avatar
Nathan Haug committed
230
231
              form_set_error($field['field_name'] .']['. $delta. '][value][link', t('Not a valid URL.'));
            }
232
233
234
235
236
237
238
239
            // 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
240
241
242
243
          }
        }
      }
      else {
244
        if ($node_field['value']['link']) {
Nathan Haug's avatar
Nathan Haug committed
245
246
247
          if (!link_validate_link($node_field['value']['link'])) {
            form_set_error($field['field_name'] .'][value][link', t('Not a valid URL.'));
          }
248
        }
Nathan Haug's avatar
Nathan Haug committed
249
250
251
252
253
254
      }
      return;
      
    case 'process form values':
      if ($field['multiple']) {
        foreach($node_field as $delta => $value) {
255
           if (!$node_field[$delta]['value']['attributes']['target'] || $node_field[$delta]['value']['attributes']['target'] == "default") {
Nathan Haug's avatar
Nathan Haug committed
256
257
258
259
260
            unset($node_field[$delta]['value']['attributes']['target']);
          }
        }
      }
      else {
261
         if (!$node_field['value']['attributes']['target'] || $node_field[$delta]['value']['attributes']['target'] == "default") {
Nathan Haug's avatar
Nathan Haug committed
262
263
264
265
266
267
268
269
270
271
          unset($node_field['value']['attributes']['target']);
        }
      }
      return;
    
    case 'submit':
      return;
  }
}

272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
 * 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,
  );
286
287
288
289
290
291
292
293
  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,
    );
  }
294
295
296
297
298
299
300
301
302
303
  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
304
305
306
/**
 * Implementation of hook_field_view() which performs any translation necessary.
 */
307
308
function _link_field_view($field, $value, $addlfields = array(), $node = NULL) {
  $attributes = array();
Nathan Haug's avatar
Nathan Haug committed
309
310
311
  // Add attributes defined at the widget level
  if (is_array($value['attributes'])) {
    foreach($value['attributes'] as $attribute => $attbvalue) {
312
313
314
      if (isset($field['attributes'][$attribute]) && $field['attributes'][$attribute] == 'user') {
        $attributes[$attribute] = $attbvalue;
      }
Nathan Haug's avatar
Nathan Haug committed
315
316
317
318
319
320
    }
  }
  // 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') {
321
        $attributes[$attribute] = $attbvalue;
Nathan Haug's avatar
Nathan Haug committed
322
323
324
325
326
      }
    }
  }
  // Build the link with a title
  if (strlen(trim($value['title']))) {
327
    $output = l($value['title'],$value['link'],$attributes);
Nathan Haug's avatar
Nathan Haug committed
328
329
330
  }
  // Build the link with the URL as the title
  else {
331
    $output = l($value['link'],$value['link'],$attributes);
Nathan Haug's avatar
Nathan Haug committed
332
333
334
335
336
337
338
339
340
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
  }
  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) {
403
404
  if (!preg_match(
    // The protocols: http://
Nathan Haug's avatar
Nathan Haug committed
405
    '/^((https|http|ftp|news):\/\/)?'.
406
407
  '('.
    // domains
Nathan Haug's avatar
Nathan Haug committed
408
409
410
      '(([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})'.
411
  ')'.
Nathan Haug's avatar
Nathan Haug committed
412
413
    // port number
    '(:([0-9]{1,4}))?'.
414
415
  // the rest of the path
  '(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.\/%=&]*)?)?'.
Nathan Haug's avatar
Nathan Haug committed
416
417
418
419
    // forward slash 0 or 1 times
    '(\/)?'.
    // end of the expression, case insensitive
    '$/i', $text, $m)) {
420
    return false;
Nathan Haug's avatar
Nathan Haug committed
421
422
  }
  else {
423
    $url = new stdClass();
Nathan Haug's avatar
Nathan Haug committed
424
425
426
427
428
429
    $url->protocol = $m[2];
    $url->hostname = strtolower($m[5]).strtolower($m[7]);
    $url->ip = $m[8];
    $url->port = $m[10];
    return $url;
  }
430
}