Projet

Général

Profil

Paste
Télécharger (51,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / link / link.module @ 87dbc3bf

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines simple link field types.
6
 */
7

    
8
define('LINK_EXTERNAL', 'external');
9
define('LINK_INTERNAL', 'internal');
10
define('LINK_FRONT', 'front');
11
define('LINK_EMAIL', 'email');
12
define('LINK_NEWS', 'news');
13
define('LINK_DOMAINS', 'aero|arpa|asia|biz|build|com|cat|ceo|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|post|pro|tel|travel|mobi|local|xxx');
14

    
15
define('LINK_TARGET_DEFAULT', 'default');
16
define('LINK_TARGET_NEW_WINDOW', '_blank');
17
define('LINK_TARGET_TOP', '_top');
18
define('LINK_TARGET_USER', 'user');
19

    
20
/**
21
 * Maximum URLs length - needs to match value in link.install.
22
 */
23
define('LINK_URL_MAX_LENGTH', 2048);
24

    
25
/**
26
 * Implements hook_field_info().
27
 */
28
function link_field_info() {
29
  return array(
30
    'link_field' => array(
31
      'label' => t('Link'),
32
      'description' => t('Store a title, href, and attributes in the database to assemble a link.'),
33
      'settings' => array(
34
        'attributes' => _link_default_attributes(),
35
        'url' => 0,
36
        'title' => 'optional',
37
        'title_value' => '',
38
        'title_maxlength' => 128,
39
        'enable_tokens' => 1,
40
        'display' => array(
41
          'url_cutoff' => 80,
42
        ),
43
      ),
44
      'instance_settings' => array(
45
        'attributes' => _link_default_attributes(),
46
        'url' => 0,
47
        'title' => 'optional',
48
        'title_value' => '',
49
        'title_label_use_field_label' => FALSE,
50
        'title_maxlength' => 128,
51
        'enable_tokens' => 1,
52
        'display' => array(
53
          'url_cutoff' => 80,
54
        ),
55
        'validate_url' => 1,
56
        'absolute_url' => 1,
57
      ),
58
      'default_widget' => 'link_field',
59
      'default_formatter' => 'link_default',
60
      // Support hook_entity_property_info() from contrib "Entity API".
61
      'property_type' => 'field_item_link',
62
      'property_callbacks' => array('link_field_property_info_callback'),
63
    ),
64
  );
65
}
66

    
67
/**
68
 * Implements hook_field_instance_settings_form().
69
 */
70
function link_field_instance_settings_form($field, $instance) {
71
  $form = array(
72
    '#element_validate' => array('link_field_settings_form_validate'),
73
  );
74

    
75
  $form['absolute_url'] = array(
76
    '#type' => 'checkbox',
77
    '#title' => t('Absolute URL'),
78
    '#default_value' => isset($instance['settings']['absolute_url']) && ($instance['settings']['absolute_url'] !== '') ? $instance['settings']['absolute_url'] : TRUE,
79
    '#description' => t('If checked, the URL will always render as an absolute URL.'),
80
  );
81

    
82
  $form['validate_url'] = array(
83
    '#type' => 'checkbox',
84
    '#title' => t('Validate URL'),
85
    '#default_value' => isset($instance['settings']['validate_url']) && ($instance['settings']['validate_url'] !== '') ? $instance['settings']['validate_url'] : TRUE,
86
    '#description' => t('If checked, the URL field will be verified as a valid URL during validation.'),
87
  );
88

    
89
  $form['url'] = array(
90
    '#type' => 'checkbox',
91
    '#title' => t('Optional URL'),
92
    '#default_value' => isset($instance['settings']['url']) ? $instance['settings']['url'] : '',
93
    '#return_value' => 'optional',
94
    '#description' => t('If checked, the URL field is optional and submitting a title alone will be acceptable. If the URL is omitted, the title will be displayed as plain text.'),
95
  );
96

    
97
  $title_options = array(
98
    'optional' => t('Optional Title'),
99
    'required' => t('Required Title'),
100
    'value' => t('Static Title'),
101
    'none' => t('No Title'),
102
  );
103

    
104
  $form['title'] = array(
105
    '#type' => 'radios',
106
    '#title' => t('Link Title'),
107
    '#default_value' => isset($instance['settings']['title']) ? $instance['settings']['title'] : 'optional',
108
    '#options' => $title_options,
109
    '#description' => t('If the link title is optional or required, a field will be displayed to the end user. If the link title is static, the link will always use the same title. If <a href="http://drupal.org/project/token">token module</a> is installed, the static title value may use any other entity field as its value. Static and token-based titles may include most inline XHTML tags such as <em>strong</em>, <em>em</em>, <em>img</em>, <em>span</em>, etc.'),
110
  );
111

    
112
  $form['title_value'] = array(
113
    '#type' => 'textfield',
114
    '#title' => t('Static title'),
115
    '#default_value' => isset($instance['settings']['title_value']) ? $instance['settings']['title_value'] : '',
116
    '#description' => t('This title will always be used if &ldquo;Static Title&rdquo; is selected above.'),
117
  );
118

    
119
  $form['title_label_use_field_label'] = array(
120
    '#type' => 'checkbox',
121
    '#title' => t('Use field label as the label for the title field'),
122
    '#default_value' => isset($instance['settings']['title_label_use_field_label']) ? $instance['settings']['title_label_use_field_label'] : FALSE,
123
    '#description' => t('If this is checked the field label will be hidden.'),
124
  );
125

    
126
  $form['title_maxlength'] = array(
127
    '#type' => 'textfield',
128
    '#title' => t('Max length of title field'),
129
    '#default_value' => isset($instance['settings']['title_maxlength']) ? $instance['settings']['title_maxlength'] : '128',
130
    '#description' => t('Set a maximum length on the title field (applies only if Link Title is optional or required).  The maximum limit is 255 characters.'),
131
    '#maxlength' => 3,
132
    '#size' => 3,
133
  );
134

    
135
  if (module_exists('token')) {
136
    // Add token module replacements fields.
137
    $form['enable_tokens'] = array(
138
      '#type' => 'checkbox',
139
      '#title' => t('Allow user-entered tokens'),
140
      '#default_value' => isset($instance['settings']['enable_tokens']) ? $instance['settings']['enable_tokens'] : 1,
141
      '#description' => t('Checking will allow users to enter tokens in URLs and Titles on the entity edit form. This does not affect the field settings on this page.'),
142
    );
143

    
144
    $entity_info = entity_get_info($instance['entity_type']);
145
    $form['tokens_help'] = array(
146
      '#theme' => 'token_tree',
147
      '#token_types' => array($entity_info['token type']),
148
      '#global_types' => TRUE,
149
      '#click_insert' => TRUE,
150
      '#dialog' => TRUE,
151
    );
152
  }
153

    
154
  $form['display'] = array(
155
    '#tree' => TRUE,
156
  );
157
  $form['display']['url_cutoff'] = array(
158
    '#type' => 'textfield',
159
    '#title' => t('URL Display Cutoff'),
160
    '#default_value' => isset($instance['settings']['display']['url_cutoff']) ? $instance['settings']['display']['url_cutoff'] : '80',
161
    '#description' => t('If the user does not include a title for this link, the URL will be used as the title. When should the link title be trimmed and finished with an elipsis (&hellip;)? Leave blank for no limit.'),
162
    '#maxlength' => 3,
163
    '#size' => 3,
164
  );
165

    
166
  $target_options = array(
167
    LINK_TARGET_DEFAULT => t('Default (no target attribute)'),
168
    LINK_TARGET_TOP => t('Open link in window root'),
169
    LINK_TARGET_NEW_WINDOW => t('Open link in new window'),
170
    LINK_TARGET_USER => t('Allow the user to choose'),
171
  );
172
  $form['attributes'] = array(
173
    '#tree' => TRUE,
174
  );
175
  $form['attributes']['target'] = array(
176
    '#type' => 'radios',
177
    '#title' => t('Link Target'),
178
    '#default_value' => empty($instance['settings']['attributes']['target']) ? LINK_TARGET_DEFAULT : $instance['settings']['attributes']['target'],
179
    '#options' => $target_options,
180
  );
181
  $form['attributes']['rel'] = array(
182
    '#type' => 'textfield',
183
    '#title' => t('Rel Attribute'),
184
    '#description' => t('When output, this link will have this rel attribute. The most common usage is <a href="http://en.wikipedia.org/wiki/Nofollow">rel=&quot;nofollow&quot;</a> which prevents some search engines from spidering entered links.'),
185
    '#default_value' => empty($instance['settings']['attributes']['rel']) ? '' : $instance['settings']['attributes']['rel'],
186
    '#field_prefix' => 'rel = "',
187
    '#field_suffix' => '"',
188
    '#size' => 20,
189
  );
190
  $rel_remove_options = array(
191
    'default' => t('Keep rel as set up above (untouched/default)'),
192
    'rel_remove_external' => t('Remove rel if given link is external'),
193
    'rel_remove_internal' => t('Remove rel if given link is internal'),
194
  );
195
  $form['rel_remove'] = array(
196
    '#type' => 'radios',
197
    '#title' => t('Remove rel attribute automatically'),
198
    '#default_value' => !isset($instance['settings']['rel_remove']) ? 'default' : $instance['settings']['rel_remove'],
199
    '#description' => t('Turn on/off if rel attribute should be removed automatically, if user given link is internal/external'),
200
    '#options' => $rel_remove_options,
201
  );
202
  $form['attributes']['configurable_class'] = array(
203
    '#title' => t("Allow the user to enter a custom link class per link"),
204
    '#type' => 'checkbox',
205
    '#default_value' => empty($instance['settings']['attributes']['configurable_class']) ? '' : $instance['settings']['attributes']['configurable_class'],
206
  );
207
  $form['attributes']['class'] = array(
208
    '#type' => 'textfield',
209
    '#title' => t('Additional CSS Class'),
210
    '#description' => t('When output, this link will have this class attribute. Multiple classes should be separated by spaces.'),
211
    '#default_value' => empty($instance['settings']['attributes']['class']) ? '' : $instance['settings']['attributes']['class'],
212
  );
213
  $form['attributes']['configurable_title'] = array(
214
    '#title' => t("Allow the user to enter a link 'title' attribute"),
215
    '#type' => 'checkbox',
216
    '#default_value' => empty($instance['settings']['attributes']['configurable_title']) ? '' : $instance['settings']['attributes']['configurable_title'],
217
  );
218
  $form['attributes']['title'] = array(
219
    '#title' => t("Default link 'title' Attribute"),
220
    '#type' => 'textfield',
221
    '#description' => t('When output, links will use this "title" attribute if the user does not provide one and when different from the link text. Read <a href="http://www.w3.org/TR/WCAG10-HTML-TECHS/#links">WCAG 1.0 Guidelines</a> for links comformances. Tokens values will be evaluated.'),
222
    '#default_value' => empty($instance['settings']['attributes']['title']) ? '' : $instance['settings']['attributes']['title'],
223
    '#field_prefix' => 'title = "',
224
    '#field_suffix' => '"',
225
    '#size' => 20,
226
  );
227
  return $form;
228
}
229

    
230
/**
231
 * #element_validate handler for link_field_instance_settings_form().
232
 */
233
function link_field_settings_form_validate($element, &$form_state, $complete_form) {
234
  if ($form_state['values']['instance']['settings']['title'] === 'value' && empty($form_state['values']['instance']['settings']['title_value'])) {
235
    form_set_error('title_value', t('A default title must be provided if the title is a static value.'));
236
  }
237
  if (!empty($form_state['values']['instance']['settings']['display']['url_cutoff']) && !is_numeric($form_state['values']['instance']['settings']['display']['url_cutoff'])) {
238
    form_set_error('display', t('URL Display Cutoff value must be numeric.'));
239
  }
240
  if (empty($form_state['values']['instance']['settings']['title_maxlength'])) {
241
    form_set_value($element['title_maxlength'], '128', $form_state);
242
  }
243
  elseif (!is_numeric($form_state['values']['instance']['settings']['title_maxlength'])) {
244
    form_set_error('title_maxlength', t('The max length of the link title must be numeric.'));
245
  }
246
  elseif ($form_state['values']['instance']['settings']['title_maxlength'] > 255) {
247
    form_set_error('title_maxlength', t('The max length of the link title cannot be greater than 255 characters.'));
248
  }
249
}
250

    
251
/**
252
 * Implements hook_field_is_empty().
253
 */
254
function link_field_is_empty($item, $field) {
255
  return empty($item['title']) && empty($item['url']);
256
}
257

    
258
/**
259
 * Implements hook_field_load().
260
 */
261
function link_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
262
  foreach ($entities as $id => $entity) {
263
    foreach ($items[$id] as $delta => $item) {
264
      $items[$id][$delta]['attributes'] = _link_load($field, $item, $instances[$id]);
265
    }
266
  }
267
}
268

    
269
/**
270
 * Implements hook_field_validate().
271
 */
272
function link_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
273
  $optional_field_found = FALSE;
274
  if ($instance['settings']['validate_url'] !== 0 || is_null($instance['settings']['validate_url']) || !isset($instance['settings']['validate_url'])) {
275
    foreach ($items as $delta => $value) {
276
      _link_validate($items[$delta], $delta, $field, $entity, $instance, $langcode, $optional_field_found, $errors);
277
    }
278
  }
279

    
280
  if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional' && $instance['required'] && !$optional_field_found) {
281
    $errors[$field['field_name']][$langcode][0][] = array(
282
      'error' => 'link_required',
283
      'message' => t('At least one title or URL must be entered.'),
284
      'error_element' => array('url' => FALSE, 'title' => TRUE),
285
    );
286
  }
287
}
288

    
289
/**
290
 * Implements hook_field_insert().
291
 */
292
function link_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
293
  foreach ($items as $delta => $value) {
294
    _link_process($items[$delta], $delta, $field, $entity);
295
  }
296
}
297

    
298
/**
299
 * Implements hook_field_update().
300
 */
301
function link_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
302
  foreach ($items as $delta => $value) {
303
    _link_process($items[$delta], $delta, $field, $entity);
304
  }
305
}
306

    
307
/**
308
 * Implements hook_field_prepare_view().
309
 */
310
function link_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
311
  foreach ($items as $entity_id => $entity_items) {
312
    foreach ($entity_items as $delta => $value) {
313
      _link_sanitize($items[$entity_id][$delta], $delta, $field, $instances[$entity_id], $entities[$entity_id]);
314
    }
315
  }
316
}
317

    
318
/**
319
 * Implements hook_field_widget_info().
320
 */
321
function link_field_widget_info() {
322
  return array(
323
    'link_field' => array(
324
      'label' => 'Link',
325
      'field types' => array('link_field'),
326
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
327
    ),
328
  );
329
}
330

    
331
/**
332
 * Implements hook_field_widget_form().
333
 */
334
function link_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
335
  $element += array(
336
    '#type' => $instance['widget']['type'],
337
    '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
338
  );
339
  return $element;
340
}
341

    
342
/**
343
 * Implements hook_field_widget_error().
344
 */
345
function link_field_widget_error($element, $error, $form, &$form_state) {
346
  if ($error['error_element']['title']) {
347
    form_error($element['title'], $error['message']);
348
  }
349
  elseif ($error['error_element']['url']) {
350
    form_error($element['url'], $error['message']);
351
  }
352
}
353

    
354
/**
355
 * Unpacks the item attributes for use.
356
 */
357
function _link_load($field, $item, $instance) {
358
  if (isset($item['attributes'])) {
359
    if (!is_array($item['attributes'])) {
360
      $item['attributes'] = unserialize($item['attributes']);
361
    }
362
    return $item['attributes'];
363
  }
364
  elseif (isset($instance['settings']['attributes'])) {
365
    return $instance['settings']['attributes'];
366
  }
367
  else {
368
    return $field['settings']['attributes'];
369
  }
370
}
371

    
372
/**
373
 * Prepares the item attributes and url for storage.
374
 */
375
function _link_process(&$item, $delta, $field, $entity) {
376
  // Trim whitespace from URL.
377
  if (!empty($item['url'])) {
378
    $item['url'] = trim($item['url']);
379
  }
380

    
381
  // If no attributes are set then make sure $item['attributes'] is an empty
382
  // array, so $field['attributes'] can override it.
383
  if (empty($item['attributes'])) {
384
    $item['attributes'] = array();
385
  }
386

    
387
  // Serialize the attributes array.
388
  if (!is_string($item['attributes'])) {
389
    $item['attributes'] = serialize($item['attributes']);
390
  }
391

    
392
  // Don't save an invalid default value (e.g. 'http://').
393
  if ((isset($field['widget']['default_value'][$delta]['url']) && $item['url'] == $field['widget']['default_value'][$delta]['url']) && is_object($entity)) {
394
    if (!link_validate_url($item['url'])) {
395
      unset($item['url']);
396
    }
397
  }
398
}
399

    
400
/**
401
 * Validates that the link field has been entered properly.
402
 */
403
function _link_validate(&$item, $delta, $field, $entity, $instance, $langcode, &$optional_field_found, &$errors) {
404
  if ($item['url'] && !(isset($instance['default_value'][$delta]['url']) && $item['url'] === $instance['default_value'][$delta]['url'] && !$instance['required'])) {
405
    // Validate the link.
406
    if (link_validate_url(trim($item['url'])) == FALSE) {
407
      $errors[$field['field_name']][$langcode][$delta][] = array(
408
        'error' => 'link_required',
409
        'message' => t('The value %value provided for %field is not a valid URL.', array(
410
          '%value' => trim($item['url']),
411
          '%field' => $instance['label'],
412
        )),
413
        'error_element' => array('url' => TRUE, 'title' => FALSE),
414
      );
415
    }
416
    // Require a title for the link if necessary.
417
    if ($instance['settings']['title'] == 'required' && strlen(trim($item['title'])) == 0) {
418
      $errors[$field['field_name']][$langcode][$delta][] = array(
419
        'error' => 'link_required',
420
        'message' => t('Titles are required for all links.'),
421
        'error_element' => array('url' => FALSE, 'title' => TRUE),
422
      );
423
    }
424
  }
425
  // Require a link if we have a title.
426
  if ($instance['settings']['url'] !== 'optional' && strlen(isset($item['title']) ? $item['title'] : NULL) > 0 && strlen(trim($item['url'])) == 0) {
427
    $errors[$field['field_name']][$langcode][$delta][] = array(
428
      'error' => 'link_required',
429
      'message' => t('You cannot enter a title without a link url.'),
430
      'error_element' => array('url' => TRUE, 'title' => FALSE),
431
    );
432
  }
433
  // In a totally bizzaro case, where URLs and titles are optional but the field is required, ensure there is at least one link.
434
  if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional'
435
      && (strlen(trim($item['url'])) !== 0 || strlen(trim($item['title'])) !== 0)) {
436
    $optional_field_found = TRUE;
437
  }
438
  // Require entire field.
439
  if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional' && $instance['required'] == 1 && !$optional_field_found && isset($instance['id'])) {
440
    $errors[$field['field_name']][$langcode][$delta][] = array(
441
      'error' => 'link_required',
442
      'message' => t('At least one title or URL must be entered.'),
443
      'error_element' => array('url' => FALSE, 'title' => TRUE),
444
    );
445
  }
446
}
447

    
448
/**
449
 * Clean up user-entered values for a link field according to field settings.
450
 *
451
 * @param array $item 
452
 *   A single link item, usually containing url, title, and attributes.
453
 * @param int $delta 
454
 *   The delta value if this field is one of multiple fields.
455
 * @param array $field 
456
 *   The CCK field definition.
457
 * @param object $entity 
458
 *   The entity containing this link.
459
 */
460
function _link_sanitize(&$item, $delta, &$field, $instance, &$entity) {
461
  // Don't try to process empty links.
462
  if (empty($item['url']) && empty($item['title'])) {
463
    return;
464
  }
465
  if (empty($item['html'])) {
466
    $item['html'] = FALSE;
467
  }
468

    
469
  // Replace URL tokens.
470
  $entity_type = $instance['entity_type'];
471
  $entity_info = entity_get_info($entity_type);
472
  $property_id = $entity_info['entity keys']['id'];
473
  $entity_token_type = isset($entity_info['token type']) ? $entity_info['token type'] : (
474
    $entity_type == 'taxonomy_term' || $entity_type == 'taxonomy_vocabulary' ? str_replace('taxonomy_', '', $entity_type) : $entity_type
475
  );
476
  if (isset($instance['settings']['enable_tokens']) && $instance['settings']['enable_tokens']) {
477
    global $user;
478
    // Load the entity if necessary for entities in views.
479
    if (isset($entity->{$property_id})) {
480
      $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
481
      $entity_loaded = array_pop($entity_loaded);
482
    }
483
    else {
484
      $entity_loaded = $entity;
485
    }
486
    $item['url'] = token_replace($item['url'], array($entity_token_type => $entity_loaded));
487
  }
488

    
489
  $type = link_validate_url($item['url']);
490
  // If the type of the URL cannot be determined and URL validation is disabled,
491
  // then assume LINK_EXTERNAL for later processing.
492
  if ($type == FALSE && $instance['settings']['validate_url'] === 0) {
493
    $type = LINK_EXTERNAL;
494
  }
495
  $url = link_cleanup_url($item['url']);
496
  $url_parts = _link_parse_url($url);
497

    
498
  if (!empty($url_parts['url'])) {
499
    $item['url'] = $url_parts['url'];
500
    $item += array(
501
      'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
502
      'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
503
      'absolute' => !empty($instance['settings']['absolute_url']),
504
      'html' => TRUE,
505
    );
506
  }
507

    
508
  // Create a shortened URL for display.
509
  if ($type == LINK_EMAIL) {
510
    $display_url = str_replace('mailto:', '', $url);
511
  }
512
  else {
513
    $display_url = url($url_parts['url'],
514
      array(
515
        'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
516
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
517
        'absolute' => !empty($instance['settings']['absolute_url']),
518
      )
519
    );
520
  }
521
  if ($instance['settings']['display']['url_cutoff'] && strlen($display_url) > $instance['settings']['display']['url_cutoff']) {
522
    $display_url = substr($display_url, 0, $instance['settings']['display']['url_cutoff']) . "...";
523
  }
524
  $item['display_url'] = $display_url;
525

    
526
  // Use the title defined at the instance level.
527
  if ($instance['settings']['title'] == 'value' && strlen(trim($instance['settings']['title_value']))) {
528
    $title = $instance['settings']['title_value'];
529
    if (function_exists('i18n_string_translate')) {
530
      $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
531
      $title = i18n_string_translate($i18n_string_name, $title);
532
    }
533
  }
534
  // Use the title defined by the user at the widget level.
535
  elseif (isset($item['title'])) {
536
    $title = $item['title'];
537
  }
538
  else {
539
    $title = '';
540
  }
541

    
542
  // Replace title tokens.
543
  if ($title && ($instance['settings']['title'] == 'value' || $instance['settings']['enable_tokens'])) {
544
    // Load the entity if necessary for entities in views.
545
    if (isset($entity->{$property_id})) {
546
      $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
547
      $entity_loaded = array_pop($entity_loaded);
548
    }
549
    else {
550
      $entity_loaded = $entity;
551
    }
552
    $title = token_replace($title, array($entity_token_type => $entity_loaded));
553
    $title = filter_xss($title, array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
554
    $item['html'] = TRUE;
555
  }
556
  $item['title'] = empty($title) ? $item['display_url'] : $title;
557

    
558
  if (!isset($item['attributes'])) {
559
    $item['attributes'] = array();
560
  }
561

    
562
  // Unserialize attributtes array if it has not been unserialized yet.
563
  if (!is_array($item['attributes'])) {
564
    $item['attributes'] = (array) unserialize($item['attributes']);
565
  }
566

    
567
  // Add default attributes.
568
  if (!is_array($instance['settings']['attributes'])) {
569
    $instance['settings']['attributes'] = _link_default_attributes();
570
  }
571
  else {
572
    $instance['settings']['attributes'] += _link_default_attributes();
573
  }
574

    
575
  // Merge item attributes with attributes defined at the field level.
576
  $item['attributes'] += $instance['settings']['attributes'];
577

    
578
  // If user is not allowed to choose target attribute, use default defined at
579
  // field level.
580
  if ($instance['settings']['attributes']['target'] != LINK_TARGET_USER) {
581
    $item['attributes']['target'] = $instance['settings']['attributes']['target'];
582
  }
583
  elseif ($item['attributes']['target'] == LINK_TARGET_USER) {
584
    $item['attributes']['target'] = LINK_TARGET_DEFAULT;
585
  }
586

    
587
  // Remove the target attribute if the default (no target) is selected.
588
  if (empty($item['attributes']) || (isset($item['attributes']['target']) && $item['attributes']['target'] == LINK_TARGET_DEFAULT)) {
589
    unset($item['attributes']['target']);
590
  }
591

    
592
  // Remove rel attribute for internal or external links if selected.
593
  if (isset($item['attributes']['rel']) && isset($instance['settings']['rel_remove']) && $instance['settings']['rel_remove'] != 'default') {
594
    if (($instance['settings']['rel_remove'] != 'rel_remove_internal' && $type != LINK_INTERNAL) ||
595
      ($instance['settings']['rel_remove'] != 'rel_remove_external' && $type != LINK_EXTERNAL)) {
596
      unset($item['attributes']['rel']);
597
    }
598
  }
599

    
600
  // Handle "title" link attribute.
601
  if (!empty($item['attributes']['title']) && module_exists('token')) {
602
    // Load the entity (necessary for entities in views).
603
    if (isset($entity->{$property_id})) {
604
      $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
605
      $entity_loaded = array_pop($entity_loaded);
606
    }
607
    else {
608
      $entity_loaded = $entity;
609
    }
610
    $item['attributes']['title'] = token_replace($item['attributes']['title'], array($entity_token_type => $entity_loaded));
611
    $item['attributes']['title'] = filter_xss($item['attributes']['title'], array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
612
  }
613
  // Handle attribute classes.
614
  if (!empty($item['attributes']['class'])) {
615
    $classes = explode(' ', $item['attributes']['class']);
616
    foreach ($classes as &$class) {
617
      $class = drupal_html_class($class);
618
    }
619
    $item['attributes']['class'] = implode(' ', $classes);
620
  }
621
  unset($item['attributes']['configurable_class']);
622

    
623
  // Remove title attribute if it's equal to link text.
624
  if (isset($item['attributes']['title']) && $item['attributes']['title'] == $item['title']) {
625
    unset($item['attributes']['title']);
626
  }
627
  unset($item['attributes']['configurable_title']);
628

    
629
  // Remove empty attributes.
630
  $item['attributes'] = array_filter($item['attributes']);
631
}
632

    
633
/**
634
 * Because parse_url doesn't work with relative urls.
635
 *
636
 * @param string $url
637
 *   URL to parse.
638
 *
639
 * @return array
640
 *   Array of url pieces - only 'url', 'query', and 'fragment'.
641
 */
642
function _link_parse_url($url) {
643
  $url_parts = array();
644
  // Separate out the anchor, if any.
645
  if (strpos($url, '#') !== FALSE) {
646
    $url_parts['fragment'] = substr($url, strpos($url, '#') + 1);
647
    $url = substr($url, 0, strpos($url, '#'));
648
  }
649
  // Separate out the query string, if any.
650
  if (strpos($url, '?') !== FALSE) {
651
    $query = substr($url, strpos($url, '?') + 1);
652
    $url_parts['query'] = _link_parse_str($query);
653
    $url = substr($url, 0, strpos($url, '?'));
654
  }
655
  $url_parts['url'] = $url;
656
  return $url_parts;
657
}
658

    
659
/**
660
 * Replaces the PHP parse_str() function.
661
 *
662
 * Because parse_str replaces the following characters in query parameters name
663
 * in order to maintain compability with deprecated register_globals directive:
664
 *
665
 *   - chr(32) ( ) (space)
666
 *   - chr(46) (.) (dot)
667
 *   - chr(91) ([) (open square bracket)
668
 *   - chr(128) - chr(159) (various)
669
 *
670
 * @param string $query
671
 *   Query to parse.
672
 *
673
 * @return array
674
 *   Array of query parameters.
675
 *
676
 * @see http://php.net/manual/en/language.variables.external.php#81080
677
 */
678
function _link_parse_str($query) {
679
  $query_array = array();
680

    
681
  $pairs = explode('&', $query);
682
  foreach ($pairs as $pair) {
683
    $name_value = explode('=', $pair, 2);
684
    $name = urldecode($name_value[0]);
685
    $value = isset($name_value[1]) ? urldecode($name_value[1]) : NULL;
686
    $query_array[$name] = $value;
687
  }
688

    
689
  return $query_array;
690
}
691

    
692
/**
693
 * Implements hook_theme().
694
 */
695
function link_theme() {
696
  return array(
697
    'link_formatter_link_default' => array(
698
      'variables' => array('element' => NULL, 'field' => NULL),
699
    ),
700
    'link_formatter_link_plain' => array(
701
      'variables' => array('element' => NULL, 'field' => NULL),
702
    ),
703
    'link_formatter_link_absolute' => array(
704
      'variables' => array('element' => NULL, 'field' => NULL),
705
    ),
706
    'link_formatter_link_domain' => array(
707
      'variables' => array('element' => NULL, 'display' => NULL, 'field' => NULL),
708
    ),
709
    'link_formatter_link_title_plain' => array(
710
      'variables' => array('element' => NULL, 'field' => NULL),
711
    ),
712
    'link_formatter_link_url' => array(
713
      'variables' => array('element' => NULL, 'field' => NULL),
714
    ),
715
    'link_formatter_link_short' => array(
716
      'variables' => array('element' => NULL, 'field' => NULL),
717
    ),
718
    'link_formatter_link_label' => array(
719
      'variables' => array('element' => NULL, 'field' => NULL),
720
    ),
721
    'link_formatter_link_separate' => array(
722
      'variables' => array('element' => NULL, 'field' => NULL),
723
    ),
724
    'link_field' => array(
725
      'render element' => 'element',
726
    ),
727
  );
728
}
729

    
730
/**
731
 * Formats a link field widget.
732
 */
733
function theme_link_field($vars) {
734
  drupal_add_css(drupal_get_path('module', 'link') . '/link.css');
735
  $element = $vars['element'];
736
  // Prefix single value link fields with the name of the field.
737
  if (empty($element['#field']['multiple'])) {
738
    if (isset($element['url']) && !isset($element['title'])) {
739
      $element['url']['#title_display'] = 'invisible';
740
    }
741
  }
742

    
743
  $output = '';
744
  $output .= '<div class="link-field-subrow clearfix">';
745
  if (isset($element['title'])) {
746
    $output .= '<div class="link-field-title link-field-column">' . drupal_render($element['title']) . '</div>';
747
  }
748
  $output .= '<div class="link-field-url' . (isset($element['title']) ? ' link-field-column' : '') . '">' . drupal_render($element['url']) . '</div>';
749
  $output .= '</div>';
750
  if (!empty($element['attributes']['target'])) {
751
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['target']) . '</div>';
752
  }
753
  if (!empty($element['attributes']['title'])) {
754
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['title']) . '</div>';
755
  }
756
  if (!empty($element['attributes']['class'])) {
757
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['class']) . '</div>';
758
  }
759
  $output .= drupal_render_children($element);
760
  return $output;
761
}
762

    
763
/**
764
 * Implements hook_element_info().
765
 */
766
function link_element_info() {
767
  $elements = array();
768
  $elements['link_field'] = array(
769
    '#input' => TRUE,
770
    '#process' => array('link_field_process'),
771
    '#theme' => 'link_field',
772
    '#theme_wrappers' => array('form_element'),
773
  );
774
  return $elements;
775
}
776

    
777
/**
778
 * Returns the default attributes and their values.
779
 */
780
function _link_default_attributes() {
781
  return array(
782
    'target' => LINK_TARGET_DEFAULT,
783
    'class' => '',
784
    'rel' => '',
785
  );
786
}
787

    
788
/**
789
 * Processes the link type element before displaying the field.
790
 *
791
 * Build the form element. When creating a form using FAPI #process,
792
 * note that $element['#value'] is already set.
793
 *
794
 * The $fields array is in $complete_form['#field_info'][$element['#field_name']].
795
 */
796
function link_field_process($element, $form_state, $complete_form) {
797
  $instance = field_widget_instance($element, $form_state);
798
  $settings = $instance['settings'];
799
  $element['url'] = array(
800
    '#type' => 'textfield',
801
    '#maxlength' => LINK_URL_MAX_LENGTH,
802
    '#title' => t('URL'),
803
    '#required' => ($element['#delta'] == 0 && $settings['url'] !== 'optional') ? $element['#required'] : FALSE,
804
    '#default_value' => isset($element['#value']['url']) ? $element['#value']['url'] : NULL,
805
  );
806
  if ($settings['title'] !== 'none' && $settings['title'] !== 'value') {
807
    // Figure out the label of the title field.
808
    if (!empty($settings['title_label_use_field_label'])) {
809
      // Use the element label as the title field label.
810
      $title_label = $element['#title'];
811
      // Hide the field label because there is no need for the duplicate labels.
812
      $element['#title_display'] = 'invisible';
813
    }
814
    else {
815
      $title_label = t('Title');
816
    }
817

    
818
    $element['title'] = array(
819
      '#type' => 'textfield',
820
      '#maxlength' => $settings['title_maxlength'],
821
      '#title' => $title_label,
822
      '#description' => t('The link title is limited to @maxlength characters maximum.', array('@maxlength' => $settings['title_maxlength'])),
823
      '#required' => ($settings['title'] == 'required' && (($element['#delta'] == 0 && $element['#required']) || !empty($element['#value']['url']))) ? TRUE : FALSE,
824
      '#default_value' => isset($element['#value']['title']) ? $element['#value']['title'] : NULL,
825
    );
826
  }
827

    
828
  // Initialize field attributes as an array if it is not an array yet.
829
  if (!is_array($settings['attributes'])) {
830
    $settings['attributes'] = array();
831
  }
832
  // Add default attributes.
833
  $settings['attributes'] += _link_default_attributes();
834
  $attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $settings['attributes'];
835
  if (!empty($settings['attributes']['target']) && $settings['attributes']['target'] == LINK_TARGET_USER) {
836
    $element['attributes']['target'] = array(
837
      '#type' => 'checkbox',
838
      '#title' => t('Open URL in a New Window'),
839
      '#return_value' => LINK_TARGET_NEW_WINDOW,
840
      '#default_value' => isset($attributes['target']) ? $attributes['target'] : FALSE,
841
    );
842
  }
843
  if (!empty($settings['attributes']['configurable_title']) && $settings['attributes']['configurable_title'] == 1) {
844
    $element['attributes']['title'] = array(
845
      '#type' => 'textfield',
846
      '#title' => t('Link "title" attribute'),
847
      '#default_value' => isset($attributes['title']) ? $attributes['title'] : '',
848
      '#field_prefix' => 'title = "',
849
      '#field_suffix' => '"',
850
    );
851
  }
852
  if (!empty($settings['attributes']['configurable_class']) && $settings['attributes']['configurable_class'] == 1) {
853
    $element['attributes']['class'] = array(
854
      '#type' => 'textfield',
855
      '#title' => t('Custom link class'),
856
      '#default_value' => isset($attributes['class']) ? $attributes['class'] : '',
857
      '#field_prefix' => 'class = "',
858
      '#field_suffix' => '"',
859
    );
860
  }
861

    
862
  // If the title field is avaliable or there are field accepts multiple values
863
  // then allow the individual field items display the required asterisk if needed.
864
  if (isset($element['title']) || isset($element['_weight'])) {
865
    // To prevent an extra required indicator, disable the required flag on the
866
    // base element since all the sub-fields are already required if desired.
867
    $element['#required'] = FALSE;
868
  }
869

    
870
  return $element;
871
}
872

    
873
/**
874
 * Implements hook_field_formatter_info().
875
 */
876
function link_field_formatter_info() {
877
  return array(
878
    'link_default' => array(
879
      'label' => t('Title, as link (default)'),
880
      'field types' => array('link_field'),
881
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
882
    ),
883
    'link_title_plain' => array(
884
      'label' => t('Title, as plain text'),
885
      'field types' => array('link_field'),
886
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
887
    ),
888
    'link_url' => array(
889
      'label' => t('URL, as link'),
890
      'field types' => array('link_field'),
891
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
892
    ),
893
    'link_plain' => array(
894
      'label' => t('URL, as plain text'),
895
      'field types' => array('link_field'),
896
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
897
    ),
898
    'link_absolute' => array(
899
      'label' => t('URL, absolute'),
900
      'field types' => array('link_field'),
901
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
902
    ),
903
    'link_domain' => array(
904
      'label' => t('Domain, as link'),
905
      'field types' => array('link_field'),
906
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
907
      'settings' => array(
908
        'strip_www' => FALSE,
909
      ),
910
    ),
911
    'link_short' => array(
912
      'label' => t('Short, as link with title "Link"'),
913
      'field types' => array('link_field'),
914
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
915
    ),
916
    'link_label' => array(
917
      'label' => t('Label, as link with label as title'),
918
      'field types' => array('link_field'),
919
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
920
    ),
921
    'link_separate' => array(
922
      'label' => t('Separate title and URL'),
923
      'field types' => array('link_field'),
924
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
925
    ),
926
  );
927
}
928

    
929
/**
930
 * Implements hook_field_formatter_settings_form().
931
 */
932
function link_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
933
  $display = $instance['display'][$view_mode];
934
  $settings = $display['settings'];
935
  $element = array();
936
  if ($display['type'] == 'link_domain') {
937
    $element['strip_www'] = array(
938
      '#title' => t('Strip www. from domain'),
939
      '#type' => 'checkbox',
940
      '#default_value' => $settings['strip_www'],
941
    );
942
  }
943
  return $element;
944
}
945

    
946
/**
947
 * Implements hook_field_formatter_settings_summary().
948
 */
949
function link_field_formatter_settings_summary($field, $instance, $view_mode) {
950
  $display = $instance['display'][$view_mode];
951
  $settings = $display['settings'];
952
  if ($display['type'] == 'link_domain') {
953
    if ($display['settings']['strip_www']) {
954
      return t('Strip www. from domain');
955
    }
956
    else {
957
      return t('Leave www. in domain');
958
    }
959
  }
960
  return '';
961
}
962

    
963
/**
964
 * Implements hook_field_formatter_view().
965
 */
966
function link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
967
  $elements = array();
968
  foreach ($items as $delta => $item) {
969
    $elements[$delta] = array(
970
      '#theme' => 'link_formatter_' . $display['type'],
971
      '#element' => $item,
972
      '#field' => $instance,
973
      '#display' => $display,
974
    );
975
  }
976
  return $elements;
977
}
978

    
979
/**
980
 * Formats a link.
981
 */
982
function theme_link_formatter_link_default($vars) {
983
  $link_options = $vars['element'];
984
  unset($link_options['title']);
985
  unset($link_options['url']);
986

    
987
  if (isset($link_options['attributes']['class'])) {
988
    $link_options['attributes']['class'] = array($link_options['attributes']['class']);
989
  }
990
  // Display a normal link if both title and URL are available.
991
  if (!empty($vars['element']['title']) && !empty($vars['element']['url'])) {
992
    return l($vars['element']['title'], $vars['element']['url'], $link_options);
993
  }
994
  // If only a title, display the title.
995
  elseif (!empty($vars['element']['title'])) {
996
    return $link_options['html'] ? $vars['element']['title'] : check_plain($vars['element']['title']);
997
  }
998
  elseif (!empty($vars['element']['url'])) {
999
    return l($vars['element']['title'], $vars['element']['url'], $link_options);
1000
  }
1001
}
1002

    
1003
/**
1004
 * Formats a link (or its title) as plain text.
1005
 */
1006
function theme_link_formatter_link_plain($vars) {
1007
  $link_options = $vars['element'];
1008
  if (isset($link_options['title'])) {
1009
    unset($link_options['title']);
1010
  }
1011
  else {
1012
    $vars['element']['title'] = '';
1013
  }
1014
  unset($link_options['url']);
1015
  return empty($vars['element']['url']) ? check_plain($vars['element']['title']) : url($vars['element']['url'], $link_options);
1016
}
1017

    
1018
/**
1019
 * Formats a link as an absolute URL.
1020
 */
1021
function theme_link_formatter_link_absolute($vars) {
1022
  $absolute = array('absolute' => TRUE);
1023
  return empty($vars['element']['url']) ? '' : url($vars['element']['url'], $absolute + $vars['element']);
1024
}
1025

    
1026
/**
1027
 * Formats a link using the URL's domain for it's link text.
1028
 */
1029
function theme_link_formatter_link_domain($vars) {
1030
  $link_options = $vars['element'];
1031
  unset($link_options['title']);
1032
  unset($link_options['url']);
1033
  $domain = parse_url($vars['element']['display_url'], PHP_URL_HOST);
1034
  if (!empty($vars['display']['settings']['strip_www'])) {
1035
    $domain = str_replace('www.', '', $domain);
1036
  }
1037
  return $vars['element']['url'] ? l($domain, $vars['element']['url'], $link_options) : '';
1038
}
1039

    
1040
/**
1041
 * Formats a link's title as plain text.
1042
 */
1043
function theme_link_formatter_link_title_plain($vars) {
1044
  return empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
1045
}
1046

    
1047
/**
1048
 * Formats a link using an alternate display URL for its link text.
1049
 */
1050
function theme_link_formatter_link_url($vars) {
1051
  $link_options = $vars['element'];
1052
  unset($link_options['title']);
1053
  unset($link_options['url']);
1054
  return $vars['element']['url'] ? l($vars['element']['display_url'], $vars['element']['url'], $link_options) : '';
1055
}
1056

    
1057
/**
1058
 * Formats a link using "Link" as the link text.
1059
 */
1060
function theme_link_formatter_link_short($vars) {
1061
  $link_options = $vars['element'];
1062
  unset($link_options['title']);
1063
  unset($link_options['url']);
1064
  return $vars['element']['url'] ? l(t('Link'), $vars['element']['url'], $link_options) : '';
1065
}
1066

    
1067
/**
1068
 * Formats a link using the field's label as link text.
1069
 */
1070
function theme_link_formatter_link_label($vars) {
1071
  $link_options = $vars['element'];
1072
  unset($link_options['title']);
1073
  unset($link_options['url']);
1074
  return $vars['element']['url'] ? l($vars['field']['label'], $vars['element']['url'], $link_options) : '';
1075
}
1076

    
1077
/**
1078
 * Formats a link as separate title and URL elements.
1079
 */
1080
function theme_link_formatter_link_separate($vars) {
1081
  $class = empty($vars['element']['attributes']['class']) ? '' : ' ' . $vars['element']['attributes']['class'];
1082
  unset($vars['element']['attributes']['class']);
1083
  $link_options = $vars['element'];
1084
  unset($link_options['title']);
1085
  unset($link_options['url']);
1086
  $title = empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
1087

    
1088
  // @TODO static html markup looks not very elegant
1089
  // needs smarter output solution and an optional title/url seperator
1090
  $url_parts = _link_parse_url($vars['element']['url']);
1091
  $output = '';
1092
  $output .= '<div class="link-item ' . $class . '">';
1093
  if (!empty($title)) {
1094
    $output .= '<div class="link-title">' . $title . '</div>';
1095
  }
1096
  $output .= '<div class="link-url">' . l($url_parts['url'], $vars['element']['url'], $link_options) . '</div>';
1097
  $output .= '</div>';
1098
  return $output;
1099
}
1100

    
1101
/**
1102
 * Implements hook_token_list().
1103
 *
1104
 * @TODO: hook_token_list no longer exists - this should change to hook_token_info().
1105
 */
1106
function link_token_list($type = 'all') {
1107
  if ($type === 'field' || $type === 'all') {
1108
    $tokens = array();
1109
    $tokens['link']['url'] = t("Link URL");
1110
    $tokens['link']['title'] = t("Link title");
1111
    $tokens['link']['view'] = t("Formatted html link");
1112
    return $tokens;
1113
  }
1114
}
1115

    
1116
/**
1117
 * Implements hook_token_values().
1118
 *
1119
 * @TODO: hook_token_values no longer exists - this should change to hook_tokens().
1120
 */
1121
function link_token_values($type, $object = NULL) {
1122
  if ($type === 'field') {
1123
    $item = $object[0];
1124

    
1125
    $tokens['url'] = $item['url'];
1126
    $tokens['title'] = $item['title'];
1127
    $tokens['view'] = isset($item['view']) ? $item['view'] : '';
1128

    
1129
    return $tokens;
1130
  }
1131
}
1132

    
1133
/**
1134
 * Implements hook_views_api().
1135
 */
1136
function link_views_api() {
1137
  return array(
1138
    'api' => 2,
1139
    'path' => drupal_get_path('module', 'link') . '/views',
1140
  );
1141
}
1142

    
1143
/**
1144
 * Forms a valid URL if possible from an entered address.
1145
 * 
1146
 * Trims whitespace and automatically adds an http:// to addresses without a
1147
 * protocol specified
1148
 *
1149
 * @param string $url
1150
 *   The url entered by the user.
1151
 * @param string $protocol
1152
 *   The protocol to be prepended to the url if one is not specified
1153
 */
1154
function link_cleanup_url($url, $protocol = 'http') {
1155
  $url = trim($url);
1156
  $type = link_validate_url($url);
1157

    
1158
  if ($type === LINK_EXTERNAL) {
1159
    // Check if there is no protocol specified.
1160
    $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
1161
    if (empty($protocol_match)) {
1162
      // But should there be? Add an automatic http:// if it starts with a domain name.
1163
      $LINK_DOMAINS = _link_domains();
1164
      $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(' . $LINK_DOMAINS . '|[a-z]{2}))/i', $url);
1165
      if (!empty($domain_match)) {
1166
        $url = $protocol . "://" . $url;
1167
      }
1168
    }
1169
  }
1170

    
1171
  return $url;
1172
}
1173

    
1174
/**
1175
 * Validates a URL.
1176
 * 
1177
 * Accepts all URLs following RFC 1738 standard for URL formation and all e-mail
1178
 * addresses following the RFC 2368 standard for mailto address formation.
1179
 *
1180
 * @param string $text
1181
 *   Url to be validated.
1182
 * 
1183
 * @return mixed
1184
 *   Returns boolean FALSE if the URL is not valid. On success, returns one of
1185
 *   the LINK_(linktype) constants.
1186
 */
1187
function link_validate_url($text) {
1188
  // @TODO Complete letters.
1189
  $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array(
1190
    "&#x00E6;", // æ
1191
    "&#x00C6;", // Æ
1192
    "&#x00C0;", // À
1193
    "&#x00E0;", // à
1194
    "&#x00C1;", // Á
1195
    "&#x00E1;", // á
1196
    "&#x00C2;", // Â
1197
    "&#x00E2;", // â
1198
    "&#x00E5;", // å
1199
    "&#x00C5;", // Å
1200
    "&#x00E4;", // ä
1201
    "&#x00C4;", // Ä
1202
    "&#x00C7;", // Ç
1203
    "&#x00E7;", // ç
1204
    "&#x00D0;", // Ð
1205
    "&#x00F0;", // ð
1206
    "&#x00C8;", // È
1207
    "&#x00E8;", // è
1208
    "&#x00C9;", // É
1209
    "&#x00E9;", // é
1210
    "&#x00CA;", // Ê
1211
    "&#x00EA;", // ê
1212
    "&#x00CB;", // Ë
1213
    "&#x00EB;", // ë
1214
    "&#x00CE;", // Î
1215
    "&#x00EE;", // î
1216
    "&#x00CF;", // Ï
1217
    "&#x00EF;", // ï
1218
    "&#x00F8;", // ø
1219
    "&#x00D8;", // Ø
1220
    "&#x00F6;", // ö
1221
    "&#x00D6;", // Ö
1222
    "&#x00D4;", // Ô
1223
    "&#x00F4;", // ô
1224
    "&#x00D5;", // Õ
1225
    "&#x00F5;", // õ
1226
    "&#x0152;", // Œ
1227
    "&#x0153;", // œ
1228
    "&#x00FC;", // ü
1229
    "&#x00DC;", // Ü
1230
    "&#x00D9;", // Ù
1231
    "&#x00F9;", // ù
1232
    "&#x00DB;", // Û
1233
    "&#x00FB;", // û
1234
    "&#x0178;", // Ÿ
1235
    "&#x00FF;", // ÿ
1236
    "&#x00D1;", // Ñ
1237
    "&#x00F1;", // ñ
1238
    "&#x00FE;", // þ
1239
    "&#x00DE;", // Þ
1240
    "&#x00FD;", // ý
1241
    "&#x00DD;", // Ý
1242
    "&#x00BF;", // ¿
1243
  )), ENT_QUOTES, 'UTF-8');
1244

    
1245
  $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
1246
    "&#x00DF;", // ß
1247
  )), ENT_QUOTES, 'UTF-8');
1248
  $allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
1249
  $LINK_DOMAINS = _link_domains();
1250

    
1251
  // Starting a parenthesis group with (?: means that it is grouped, but is not captured.
1252
  $protocol = '((?:' . implode("|", $allowed_protocols) . '):\/\/)';
1253
  $authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w" . $LINK_ICHARS . "\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
1254
  $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*(' . $LINK_DOMAINS . '|[a-z]{2}))?)';
1255
  $ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
1256
  $ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
1257
  $port = '(?::([0-9]{1,5}))';
1258

    
1259
  // Pattern specific to external links.
1260
  $external_pattern = '/^' . $protocol . '?' . $authentication . '?(' . $domain . '|' . $ipv4 . '|' . $ipv6 . ' |localhost)' . $port . '?';
1261

    
1262
  // Pattern specific to internal links.
1263
  $internal_pattern = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\] ]+)";
1264
  $internal_pattern_file = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)]+)$/i";
1265

    
1266
  $directories = "(?:\/[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'#!():;*@\[\]]*)*";
1267
  // Yes, four backslashes == a single backslash.
1268
  $query = "(?:\/?\?([?a-z0-9" . $LINK_ICHARS . "+_|\-\.~\/\\\\%=&,$'!():;*@\[\]{} ]*))";
1269
  $anchor = "(?:#[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
1270

    
1271
  // The rest of the path for a standard URL.
1272
  $end = $directories . '?' . $query . '?' . $anchor . '?' . '$/i';
1273

    
1274
  $message_id = '[^@].*@' . $domain;
1275
  $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
1276
  $news_pattern = '/^news:(' . $newsgroup_name . '|' . $message_id . ')$/i';
1277

    
1278
  $user = '[a-zA-Z0-9' . $LINK_ICHARS . '_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
1279
  $email_pattern = '/^mailto:' . $user . '@' . '(?:' . $domain . '|' . $ipv4 . '|' . $ipv6 . '|localhost)' . $query . '?$/';
1280

    
1281
  if (strpos($text, '<front>') === 0) {
1282
    return LINK_FRONT;
1283
  }
1284
  if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
1285
    return LINK_EMAIL;
1286
  }
1287
  if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
1288
    return LINK_NEWS;
1289
  }
1290
  if (preg_match($internal_pattern . $end, $text)) {
1291
    return LINK_INTERNAL;
1292
  }
1293
  if (preg_match($external_pattern . $end, $text)) {
1294
    return LINK_EXTERNAL;
1295
  }
1296
  if (preg_match($internal_pattern_file, $text)) {
1297
    return LINK_INTERNAL;
1298
  }
1299

    
1300
  return FALSE;
1301
}
1302

    
1303
/**
1304
 * Returns the list of allowed domains, including domains added by admins via variable_set/$config.
1305
 */
1306
function _link_domains() {
1307
  $link_extra_domains = variable_get('link_extra_domains', array());
1308
  return empty($link_extra_domains) ? LINK_DOMAINS : LINK_DOMAINS . '|' . implode('|', $link_extra_domains);
1309
}
1310

    
1311
/**
1312
 * Implements hook_migrate_field_alter().
1313
 */
1314
function link_content_migrate_field_alter(&$field_value, $instance_value) {
1315
  if ($field_value['type'] == 'link') {
1316
    // Adjust the field type.
1317
    $field_value['type'] = 'link_field';
1318
    // Remove settings that are now on the instance.
1319
    foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
1320
      unset($field_value['settings'][$setting]);
1321
    }
1322
  }
1323
}
1324

    
1325
/**
1326
 * Implements hook_migrate_instance_alter().
1327
 *
1328
 * Widget type also changed to link_field.
1329
 */
1330
function link_content_migrate_instance_alter(&$instance_value, $field_value) {
1331
  if ($field_value['type'] == 'link') {
1332
    // Grab settings that were previously on the field.
1333
    foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
1334
      if (isset($field_value['settings'][$setting])) {
1335
        $instance_value['settings'][$setting] = $field_value['settings'][$setting];
1336
      }
1337
    }
1338
    // Adjust widget type.
1339
    if ($instance_value['widget']['type'] == 'link') {
1340
      $instance_value['widget']['type'] = 'link_field';
1341
    }
1342
    // Adjust formatter types.
1343
    foreach ($instance_value['display'] as $context => $settings) {
1344
      if (in_array($settings['type'], array('default', 'title_plain', 'url', 'plain', 'short', 'label', 'separate'))) {
1345
        $instance_value['display'][$context]['type'] = 'link_' . $settings['type'];
1346
      }
1347
    }
1348
  }
1349
}
1350

    
1351
/**
1352
 * Implements hook_field_settings_form().
1353
 */
1354
function link_field_settings_form() {
1355
  return array();
1356
}
1357

    
1358
/**
1359
 * Additional callback to adapt the property info of link fields.
1360
 * 
1361
 * @see entity_metadata_field_entity_property_info()
1362
 */
1363
function link_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
1364
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
1365
  // Define a data structure so it's possible to deal with both the link title
1366
  // and URL.
1367
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
1368
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
1369

    
1370
  // Auto-create the field item as soon as a property is set.
1371
  $property['auto creation'] = 'link_field_item_create';
1372

    
1373
  $property['property info'] = link_field_item_property_info();
1374
  $property['property info']['url']['required'] = !$instance['settings']['url'];
1375
  $property['property info']['title']['required'] = ($instance['settings']['title'] == 'required');
1376
  if ($instance['settings']['title'] == 'none') {
1377
    unset($property['property info']['title']);
1378
  }
1379
  unset($property['query callback']);
1380
}
1381

    
1382
/**
1383
 * Callback for creating a new, empty link field item.
1384
 *
1385
 * @see link_field_property_info_callback()
1386
 */
1387
function link_field_item_create() {
1388
  return array('title' => NULL, 'url' => NULL);
1389
}
1390

    
1391
/**
1392
 * Defines info for the properties of the link-field item data structure.
1393
 */
1394
function link_field_item_property_info() {
1395
  $properties['title'] = array(
1396
    'type' => 'text',
1397
    'label' => t('The title of the link.'),
1398
    'setter callback' => 'entity_property_verbatim_set',
1399
  );
1400
  $properties['url'] = array(
1401
    'type' => 'uri',
1402
    'label' => t('The URL of the link.'),
1403
    'setter callback' => 'entity_property_verbatim_set',
1404
  );
1405
  $properties['attributes'] = array(
1406
    'type' => 'struct',
1407
    'label' => t('The attributes of the link.'),
1408
    'setter callback' => 'entity_property_verbatim_set',
1409
    'getter callback' => 'link_attribute_property_get',
1410
  );
1411
  return $properties;
1412
}
1413

    
1414
/**
1415
 * Entity property info getter callback for link attributes.
1416
 */
1417
function link_attribute_property_get($data, array $options, $name, $type, $info) {
1418
  return isset($data[$name]) ? array_filter($data[$name]) : array();
1419
}
1420

    
1421
/**
1422
 * Implements hook_field_update_instance().
1423
 */
1424
function link_field_update_instance($instance, $prior_instance) {
1425
  if (function_exists('i18n_string_update') && $instance['widget']['type'] == 'link_field' && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {
1426
    $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
1427
    i18n_string_update($i18n_string_name, $instance['settings']['title_value']);
1428
  }
1429
}
1430

    
1431
/**
1432
 * Implements hook_i18n_string_list_TEXTGROUP_alter().
1433
 */
1434
function link_i18n_string_list_field_alter(&$strings, $type = NULL, $object = NULL) {
1435
  if ($type != 'field_instance' || !is_array($object) || !isset($object['widget']['type'])) {
1436
    return;
1437
  }
1438
  if ($object['widget']['type'] == 'link_field' && isset($object['settings']['title_value'])) {
1439
    $strings['field'][$object['field_name']][$object['bundle']]['title_value']['string'] = $object['settings']['title_value'];
1440
  }
1441
}