Projet

Général

Profil

Paste
Télécharger (53,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / link / link.module @ 7fe061e8

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. Only alphanumeric characters and hyphens are allowed'),
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, $instance);
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, $instance);
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
 * @param $item
376
 *    Link field values.
377
 *
378
 * @param $delta
379
 *    The sequence number for current values.
380
 *
381
 * @param $field
382
 *    The field structure array.
383
 *
384
 * @param $entity
385
 *    Entity object.
386
 *
387
 * @param $instance
388
 *    The instance structure for $field on $entity's bundle.
389
 *
390
 */
391
function _link_process(&$item, $delta, $field, $entity, $instance) {
392
  // Trim whitespace from URL.
393
  if (!empty($item['url'])) {
394
    $item['url'] = trim($item['url']);
395
  }
396

    
397
  // If no attributes are set then make sure $item['attributes'] is an empty
398
  // array, so $field['attributes'] can override it.
399
  if (empty($item['attributes'])) {
400
    $item['attributes'] = array();
401
  }
402

    
403
  // Serialize the attributes array.
404
  if (!is_string($item['attributes'])) {
405
    $item['attributes'] = serialize($item['attributes']);
406
  }
407

    
408
  // Don't save an invalid default value (e.g. 'http://').
409
  if ((isset($field['widget']['default_value'][$delta]['url']) && $item['url'] == $field['widget']['default_value'][$delta]['url']) && is_object($entity)) {
410
    $langcode = !empty($entity) ? field_language($instance['entity_type'], $entity, $instance['field_name']) : LANGUAGE_NONE;
411
    if (!link_validate_url($item['url'], $langcode)) {
412
      unset($item['url']);
413
    }
414
  }
415
}
416

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

    
465
/**
466
 * Clean up user-entered values for a link field according to field settings.
467
 *
468
 * @param array $item 
469
 *   A single link item, usually containing url, title, and attributes.
470
 * @param int $delta 
471
 *   The delta value if this field is one of multiple fields.
472
 * @param array $field 
473
 *   The CCK field definition.
474
 * @param object $entity 
475
 *   The entity containing this link.
476
 */
477
function _link_sanitize(&$item, $delta, &$field, $instance, &$entity) {
478
  // Don't try to process empty links.
479
  if (empty($item['url']) && empty($item['title'])) {
480
    return;
481
  }
482
  if (empty($item['html'])) {
483
    $item['html'] = FALSE;
484
  }
485

    
486
  // Replace URL tokens.
487
  $entity_type = $instance['entity_type'];
488
  $entity_info = entity_get_info($entity_type);
489
  $property_id = $entity_info['entity keys']['id'];
490
  $entity_token_type = isset($entity_info['token type']) ? $entity_info['token type'] : (
491
    $entity_type == 'taxonomy_term' || $entity_type == 'taxonomy_vocabulary' ? str_replace('taxonomy_', '', $entity_type) : $entity_type
492
  );
493
  if (isset($instance['settings']['enable_tokens']) && $instance['settings']['enable_tokens']) {
494
    $text_tokens = token_scan($item['url']);
495
    if (!empty($text_tokens)) {
496
      // Load the entity if necessary for entities in views.
497
      if (isset($entity->{$property_id})) {
498
        $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
499
        $entity_loaded = array_pop($entity_loaded);
500
      }
501
      else {
502
        $entity_loaded = $entity;
503
      }
504
      $item['url'] = token_replace($item['url'], array($entity_token_type => $entity_loaded));
505
    }
506
  }
507

    
508
  $type = link_url_type($item['url']);
509
  // If the type of the URL cannot be determined and URL validation is disabled,
510
  // then assume LINK_EXTERNAL for later processing.
511
  if ($type == FALSE && $instance['settings']['validate_url'] === 0) {
512
    $type = LINK_EXTERNAL;
513
  }
514
  $url = link_cleanup_url($item['url']);
515
  $url_parts = _link_parse_url($url);
516

    
517
  if (!empty($url_parts['url'])) {
518
    $item['url'] = url($url_parts['url'],
519
      array('query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
520
      'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
521
      'absolute' => !empty($instance['settings']['absolute_url']),
522
      'html' => TRUE,
523
      )
524
    );
525
  }
526

    
527
  // Create a shortened URL for display.
528
  if ($type == LINK_EMAIL) {
529
    $display_url = str_replace('mailto:', '', $url);
530
  }
531
  else {
532
    $display_url = url($url_parts['url'],
533
      array(
534
        'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
535
        'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
536
        'absolute' => !empty($instance['settings']['absolute_url']),
537
      )
538
    );
539
  }
540
  if ($instance['settings']['display']['url_cutoff'] && strlen($display_url) > $instance['settings']['display']['url_cutoff']) {
541
    $display_url = substr($display_url, 0, $instance['settings']['display']['url_cutoff']) . "...";
542
  }
543
  $item['display_url'] = $display_url;
544

    
545
  // Use the title defined at the instance level.
546
  if ($instance['settings']['title'] == 'value' && strlen(trim($instance['settings']['title_value']))) {
547
    $title = $instance['settings']['title_value'];
548
    if (function_exists('i18n_string_translate')) {
549
      $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
550
      $title = i18n_string_translate($i18n_string_name, $title);
551
    }
552
  }
553
  // Use the title defined by the user at the widget level.
554
  elseif (isset($item['title'])) {
555
    $title = $item['title'];
556
  }
557
  else {
558
    $title = '';
559
  }
560

    
561
  // Replace title tokens.
562
  if ($title && ($instance['settings']['title'] == 'value' || $instance['settings']['enable_tokens'])) {
563
    $text_tokens = token_scan($title);
564
    if (!empty($text_tokens)) {
565
      // Load the entity if necessary for entities in views.
566
      if (isset($entity->{$property_id})) {
567
        $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
568
        $entity_loaded = array_pop($entity_loaded);
569
      }
570
      else {
571
        $entity_loaded = $entity;
572
      }
573
      $title = token_replace($title, array($entity_token_type => $entity_loaded));
574
    }
575
    $title = filter_xss($title, array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
576
    $item['html'] = TRUE;
577
  }
578
  $item['title'] = empty($title) ? $item['display_url'] : $title;
579

    
580
  if (!isset($item['attributes'])) {
581
    $item['attributes'] = array();
582
  }
583

    
584
  // Unserialize attributtes array if it has not been unserialized yet.
585
  if (!is_array($item['attributes'])) {
586
    $item['attributes'] = (array) unserialize($item['attributes']);
587
  }
588

    
589
  // Add default attributes.
590
  if (!is_array($instance['settings']['attributes'])) {
591
    $instance['settings']['attributes'] = _link_default_attributes();
592
  }
593
  else {
594
    $instance['settings']['attributes'] += _link_default_attributes();
595
  }
596

    
597
  // Merge item attributes with attributes defined at the field level.
598
  $item['attributes'] += $instance['settings']['attributes'];
599

    
600
  // If user is not allowed to choose target attribute, use default defined at
601
  // field level.
602
  if ($instance['settings']['attributes']['target'] != LINK_TARGET_USER) {
603
    $item['attributes']['target'] = $instance['settings']['attributes']['target'];
604
  }
605
  elseif ($item['attributes']['target'] == LINK_TARGET_USER) {
606
    $item['attributes']['target'] = LINK_TARGET_DEFAULT;
607
  }
608

    
609
  // Remove the target attribute if the default (no target) is selected.
610
  if (empty($item['attributes']) || (isset($item['attributes']['target']) && $item['attributes']['target'] == LINK_TARGET_DEFAULT)) {
611
    unset($item['attributes']['target']);
612
  }
613

    
614
  // Remove rel attribute for internal or external links if selected.
615
  if (isset($item['attributes']['rel']) && isset($instance['settings']['rel_remove']) && $instance['settings']['rel_remove'] != 'default') {
616
    if (($instance['settings']['rel_remove'] != 'rel_remove_internal' && $type != LINK_INTERNAL) ||
617
      ($instance['settings']['rel_remove'] != 'rel_remove_external' && $type != LINK_EXTERNAL)) {
618
      unset($item['attributes']['rel']);
619
    }
620
  }
621

    
622
  // Handle "title" link attribute.
623
  if (!empty($item['attributes']['title']) && module_exists('token')) {
624
    $text_tokens = token_scan($item['attributes']['title']);
625
      if (!empty($text_tokens)) {
626
      // Load the entity (necessary for entities in views).
627
      if (isset($entity->{$property_id})) {
628
        $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
629
        $entity_loaded = array_pop($entity_loaded);
630
      }
631
      else {
632
        $entity_loaded = $entity;
633
      }
634
      $item['attributes']['title'] = token_replace($item['attributes']['title'], array($entity_token_type => $entity_loaded));
635
    }
636
    $item['attributes']['title'] = filter_xss($item['attributes']['title'], array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
637
  }
638
  // Handle attribute classes.
639
  if (!empty($item['attributes']['class'])) {
640
    $classes = explode(' ', $item['attributes']['class']);
641
    foreach ($classes as &$class) {
642
      $class = drupal_clean_css_identifier($class);
643
    }
644
    $item['attributes']['class'] = implode(' ', $classes);
645
  }
646
  unset($item['attributes']['configurable_class']);
647

    
648
  // Remove title attribute if it's equal to link text.
649
  if (isset($item['attributes']['title']) && $item['attributes']['title'] == $item['title']) {
650
    unset($item['attributes']['title']);
651
  }
652
  unset($item['attributes']['configurable_title']);
653

    
654
  // Remove empty attributes.
655
  $item['attributes'] = array_filter($item['attributes']);
656
}
657

    
658
/**
659
 * Because parse_url doesn't work with relative urls.
660
 *
661
 * @param string $url
662
 *   URL to parse.
663
 *
664
 * @return array
665
 *   Array of url pieces - only 'url', 'query', and 'fragment'.
666
 */
667
function _link_parse_url($url) {
668
  $url_parts = array();
669
  // Separate out the anchor, if any.
670
  if (strpos($url, '#') !== FALSE) {
671
    $url_parts['fragment'] = substr($url, strpos($url, '#') + 1);
672
    $url = substr($url, 0, strpos($url, '#'));
673
  }
674
  // Separate out the query string, if any.
675
  if (strpos($url, '?') !== FALSE) {
676
    $query = substr($url, strpos($url, '?') + 1);
677
    $url_parts['query'] = _link_parse_str($query);
678
    $url = substr($url, 0, strpos($url, '?'));
679
  }
680
  $url_parts['url'] = $url;
681
  return $url_parts;
682
}
683

    
684
/**
685
 * Replaces the PHP parse_str() function.
686
 *
687
 * Because parse_str replaces the following characters in query parameters name
688
 * in order to maintain compatibility with deprecated register_globals directive:
689
 *
690
 *   - chr(32) ( ) (space)
691
 *   - chr(46) (.) (dot)
692
 *   - chr(91) ([) (open square bracket)
693
 *   - chr(128) - chr(159) (various)
694
 *
695
 * @param string $query
696
 *   Query to parse.
697
 *
698
 * @return array
699
 *   Array of query parameters.
700
 *
701
 * @see http://php.net/manual/en/language.variables.external.php#81080
702
 */
703
function _link_parse_str($query) {
704
  $query_array = array();
705

    
706
  $pairs = explode('&', $query);
707
  foreach ($pairs as $pair) {
708
    $name_value = explode('=', $pair, 2);
709
    $name = urldecode($name_value[0]);
710
    $value = isset($name_value[1]) ? urldecode($name_value[1]) : NULL;
711
    $query_array[$name] = $value;
712
  }
713

    
714
  return $query_array;
715
}
716

    
717
/**
718
 * Implements hook_theme().
719
 */
720
function link_theme() {
721
  return array(
722
    'link_formatter_link_default' => array(
723
      'variables' => array('element' => NULL, 'field' => NULL),
724
    ),
725
    'link_formatter_link_plain' => array(
726
      'variables' => array('element' => NULL, 'field' => NULL),
727
    ),
728
    'link_formatter_link_host' => array(
729
      'variables' => array('element' => NULL),
730
    ),
731
    'link_formatter_link_absolute' => array(
732
      'variables' => array('element' => NULL, 'field' => NULL),
733
    ),
734
    'link_formatter_link_domain' => array(
735
      'variables' => array('element' => NULL, 'display' => NULL, 'field' => NULL),
736
    ),
737
    'link_formatter_link_title_plain' => array(
738
      'variables' => array('element' => NULL, 'field' => NULL),
739
    ),
740
    'link_formatter_link_url' => array(
741
      'variables' => array('element' => NULL, 'field' => NULL),
742
    ),
743
    'link_formatter_link_short' => array(
744
      'variables' => array('element' => NULL, 'field' => NULL),
745
    ),
746
    'link_formatter_link_label' => array(
747
      'variables' => array('element' => NULL, 'field' => NULL),
748
    ),
749
    'link_formatter_link_separate' => array(
750
      'variables' => array('element' => NULL, 'field' => NULL),
751
    ),
752
    'link_field' => array(
753
      'render element' => 'element',
754
    ),
755
  );
756
}
757

    
758
/**
759
 * Formats a link field widget.
760
 */
761
function theme_link_field($vars) {
762
  drupal_add_css(drupal_get_path('module', 'link') . '/link.css');
763
  $element = $vars['element'];
764
  // Prefix single value link fields with the name of the field.
765
  if (empty($element['#field']['multiple'])) {
766
    if (isset($element['url']) && !isset($element['title'])) {
767
      $element['url']['#title_display'] = 'invisible';
768
    }
769
  }
770

    
771
  $output = '';
772
  $output .= '<div class="link-field-subrow clearfix">';
773
  if (isset($element['title'])) {
774
    $output .= '<div class="link-field-title link-field-column">' . drupal_render($element['title']) . '</div>';
775
  }
776
  $output .= '<div class="link-field-url' . (isset($element['title']) ? ' link-field-column' : '') . '">' . drupal_render($element['url']) . '</div>';
777
  $output .= '</div>';
778
  if (!empty($element['attributes']['target'])) {
779
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['target']) . '</div>';
780
  }
781
  if (!empty($element['attributes']['title'])) {
782
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['title']) . '</div>';
783
  }
784
  if (!empty($element['attributes']['class'])) {
785
    $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['class']) . '</div>';
786
  }
787
  $output .= drupal_render_children($element);
788
  return $output;
789
}
790

    
791
/**
792
 * Implements hook_element_info().
793
 */
794
function link_element_info() {
795
  $elements = array();
796
  $elements['link_field'] = array(
797
    '#input' => TRUE,
798
    '#process' => array('link_field_process'),
799
    '#theme' => 'link_field',
800
    '#theme_wrappers' => array('form_element'),
801
  );
802
  return $elements;
803
}
804

    
805
/**
806
 * Returns the default attributes and their values.
807
 */
808
function _link_default_attributes() {
809
  return array(
810
    'target' => LINK_TARGET_DEFAULT,
811
    'class' => '',
812
    'rel' => '',
813
  );
814
}
815

    
816
/**
817
 * Processes the link type element before displaying the field.
818
 *
819
 * Build the form element. When creating a form using FAPI #process,
820
 * note that $element['#value'] is already set.
821
 *
822
 * The $fields array is in $complete_form['#field_info'][$element['#field_name']].
823
 */
824
function link_field_process($element, $form_state, $complete_form) {
825
  $instance = field_widget_instance($element, $form_state);
826
  $settings = $instance['settings'];
827
  $element['url'] = array(
828
    '#type' => 'textfield',
829
    '#maxlength' => LINK_URL_MAX_LENGTH,
830
    '#title' => t('URL'),
831
    '#required' => ($element['#delta'] == 0 && $settings['url'] !== 'optional') ? $element['#required'] : FALSE,
832
    '#default_value' => isset($element['#value']['url']) ? $element['#value']['url'] : NULL,
833
  );
834
  if ($settings['title'] !== 'none' && $settings['title'] !== 'value') {
835
    // Figure out the label of the title field.
836
    if (!empty($settings['title_label_use_field_label'])) {
837
      // Use the element label as the title field label.
838
      $title_label = $element['#title'];
839
      // Hide the field label because there is no need for the duplicate labels.
840
      $element['#title_display'] = 'invisible';
841
    }
842
    else {
843
      $title_label = t('Title');
844
    }
845

    
846
    $element['title'] = array(
847
      '#type' => 'textfield',
848
      '#maxlength' => $settings['title_maxlength'],
849
      '#title' => $title_label,
850
      '#description' => t('The link title is limited to @maxlength characters maximum.', array('@maxlength' => $settings['title_maxlength'])),
851
      '#required' => ($settings['title'] == 'required' && (($element['#delta'] == 0 && $element['#required']) || !empty($element['#value']['url']))) ? TRUE : FALSE,
852
      '#default_value' => isset($element['#value']['title']) ? $element['#value']['title'] : NULL,
853
    );
854
  }
855

    
856
  // Initialize field attributes as an array if it is not an array yet.
857
  if (!is_array($settings['attributes'])) {
858
    $settings['attributes'] = array();
859
  }
860
  // Add default attributes.
861
  $settings['attributes'] += _link_default_attributes();
862
  $attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $settings['attributes'];
863
  if (!empty($settings['attributes']['target']) && $settings['attributes']['target'] == LINK_TARGET_USER) {
864
    $element['attributes']['target'] = array(
865
      '#type' => 'checkbox',
866
      '#title' => t('Open URL in a New Window'),
867
      '#return_value' => LINK_TARGET_NEW_WINDOW,
868
      '#default_value' => isset($attributes['target']) ? $attributes['target'] : FALSE,
869
    );
870
  }
871
  if (!empty($settings['attributes']['configurable_title']) && $settings['attributes']['configurable_title'] == 1) {
872
    $element['attributes']['title'] = array(
873
      '#type' => 'textfield',
874
      '#title' => t('Link "title" attribute'),
875
      '#default_value' => isset($attributes['title']) ? $attributes['title'] : '',
876
      '#field_prefix' => 'title = "',
877
      '#field_suffix' => '"',
878
    );
879
  }
880
  if (!empty($settings['attributes']['configurable_class']) && $settings['attributes']['configurable_class'] == 1) {
881
    $element['attributes']['class'] = array(
882
      '#type' => 'textfield',
883
      '#title' => t('Custom link class'),
884
      '#default_value' => isset($attributes['class']) ? $attributes['class'] : '',
885
      '#field_prefix' => 'class = "',
886
      '#field_suffix' => '"',
887
    );
888
  }
889

    
890
  // If the title field is available or there are field accepts multiple values
891
  // then allow the individual field items display the required asterisk if needed.
892
  if (isset($element['title']) || isset($element['_weight'])) {
893
    // To prevent an extra required indicator, disable the required flag on the
894
    // base element since all the sub-fields are already required if desired.
895
    $element['#required'] = FALSE;
896
  }
897

    
898
  return $element;
899
}
900

    
901
/**
902
 * Implements hook_field_formatter_info().
903
 */
904
function link_field_formatter_info() {
905
  return array(
906
    'link_default' => array(
907
      'label' => t('Title, as link (default)'),
908
      'field types' => array('link_field'),
909
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
910
    ),
911
    'link_title_plain' => array(
912
      'label' => t('Title, as plain text'),
913
      'field types' => array('link_field'),
914
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
915
    ),
916
    'link_host' => array(
917
      'label' => t('Host, as plain text'),
918
      'field types' => array('link_field'),
919
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
920
    ),
921
    'link_url' => array(
922
      'label' => t('URL, as link'),
923
      'field types' => array('link_field'),
924
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
925
    ),
926
    'link_plain' => array(
927
      'label' => t('URL, as plain text'),
928
      'field types' => array('link_field'),
929
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
930
    ),
931
    'link_absolute' => array(
932
      'label' => t('URL, absolute'),
933
      'field types' => array('link_field'),
934
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
935
    ),
936
    'link_domain' => array(
937
      'label' => t('Domain, as link'),
938
      'field types' => array('link_field'),
939
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
940
      'settings' => array(
941
        'strip_www' => FALSE,
942
      ),
943
    ),
944
    'link_short' => array(
945
      'label' => t('Short, as link with title "Link"'),
946
      'field types' => array('link_field'),
947
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
948
    ),
949
    'link_label' => array(
950
      'label' => t('Label, as link with label as title'),
951
      'field types' => array('link_field'),
952
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
953
    ),
954
    'link_separate' => array(
955
      'label' => t('Separate title and URL'),
956
      'field types' => array('link_field'),
957
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
958
    ),
959
  );
960
}
961

    
962
/**
963
 * Implements hook_field_formatter_settings_form().
964
 */
965
function link_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
966
  $display = $instance['display'][$view_mode];
967
  $settings = $display['settings'];
968
  $element = array();
969
  if ($display['type'] == 'link_domain') {
970
    $element['strip_www'] = array(
971
      '#title' => t('Strip www. from domain'),
972
      '#type' => 'checkbox',
973
      '#default_value' => $settings['strip_www'],
974
    );
975
  }
976
  return $element;
977
}
978

    
979
/**
980
 * Implements hook_field_formatter_settings_summary().
981
 */
982
function link_field_formatter_settings_summary($field, $instance, $view_mode) {
983
  $display = $instance['display'][$view_mode];
984
  $settings = $display['settings'];
985
  if ($display['type'] == 'link_domain') {
986
    if ($display['settings']['strip_www']) {
987
      return t('Strip www. from domain');
988
    }
989
    else {
990
      return t('Leave www. in domain');
991
    }
992
  }
993
  return '';
994
}
995

    
996
/**
997
 * Implements hook_field_formatter_view().
998
 */
999
function link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
1000
  $elements = array();
1001
  foreach ($items as $delta => $item) {
1002
    $elements[$delta] = array(
1003
      '#theme' => 'link_formatter_' . $display['type'],
1004
      '#element' => $item,
1005
      '#field' => $instance,
1006
      '#display' => $display,
1007
    );
1008
  }
1009
  return $elements;
1010
}
1011

    
1012
/**
1013
 * Formats a link.
1014
 */
1015
function theme_link_formatter_link_default($vars) {
1016
  $link_options = $vars['element'];
1017
  unset($link_options['title']);
1018
  unset($link_options['url']);
1019

    
1020
  if (isset($link_options['attributes']['class'])) {
1021
    $link_options['attributes']['class'] = array($link_options['attributes']['class']);
1022
  }
1023
  // Display a normal link if both title and URL are available.
1024
  if (!empty($vars['element']['title']) && !empty($vars['element']['url'])) {
1025
    return l($vars['element']['title'], $vars['element']['url'], $link_options);
1026
  }
1027
  // If only a title, display the title.
1028
  elseif (!empty($vars['element']['title'])) {
1029
    return $link_options['html'] ? $vars['element']['title'] : check_plain($vars['element']['title']);
1030
  }
1031
  elseif (!empty($vars['element']['url'])) {
1032
    return l($vars['element']['title'], $vars['element']['url'], $link_options);
1033
  }
1034
}
1035

    
1036
/**
1037
 * Formats a link (or its title) as plain text.
1038
 */
1039
function theme_link_formatter_link_plain($vars) {
1040
  $link_options = $vars['element'];
1041
  if (isset($link_options['title'])) {
1042
    unset($link_options['title']);
1043
  }
1044
  else {
1045
    $vars['element']['title'] = '';
1046
  }
1047
  unset($link_options['url']);
1048
  return empty($vars['element']['url']) ? check_plain($vars['element']['title']) : url($vars['element']['url'], $link_options);
1049
}
1050

    
1051
/**
1052
 * Theme function for 'host' text field formatter.
1053
 */
1054
function theme_link_formatter_link_host($vars) {
1055
  $host = @parse_url($vars['element']['url']);
1056
  return isset($host['host']) ? check_plain($host['host']) : '';
1057
}
1058

    
1059
/**
1060
 * Formats a link as an absolute URL.
1061
 */
1062
function theme_link_formatter_link_absolute($vars) {
1063
  $absolute = array('absolute' => TRUE);
1064
  return empty($vars['element']['url']) ? '' : url($vars['element']['url'], $absolute + $vars['element']);
1065
}
1066

    
1067
/**
1068
 * Formats a link using the URL's domain for it's link text.
1069
 */
1070
function theme_link_formatter_link_domain($vars) {
1071
  $link_options = $vars['element'];
1072
  unset($link_options['title']);
1073
  unset($link_options['url']);
1074
  $domain = parse_url($vars['element']['display_url'], PHP_URL_HOST);
1075
  if (!empty($vars['display']['settings']['strip_www'])) {
1076
    $domain = str_replace('www.', '', $domain);
1077
  }
1078
  return $vars['element']['url'] ? l($domain, $vars['element']['url'], $link_options) : '';
1079
}
1080

    
1081
/**
1082
 * Formats a link's title as plain text.
1083
 */
1084
function theme_link_formatter_link_title_plain($vars) {
1085
  return empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
1086
}
1087

    
1088
/**
1089
 * Formats a link using an alternate display URL for its link text.
1090
 */
1091
function theme_link_formatter_link_url($vars) {
1092
  $link_options = $vars['element'];
1093
  unset($link_options['title']);
1094
  unset($link_options['url']);
1095
  return $vars['element']['url'] ? l($vars['element']['display_url'], $vars['element']['url'], $link_options) : '';
1096
}
1097

    
1098
/**
1099
 * Formats a link using "Link" as the link text.
1100
 */
1101
function theme_link_formatter_link_short($vars) {
1102
  $link_options = $vars['element'];
1103
  unset($link_options['title']);
1104
  unset($link_options['url']);
1105
  return $vars['element']['url'] ? l(t('Link'), $vars['element']['url'], $link_options) : '';
1106
}
1107

    
1108
/**
1109
 * Formats a link using the field's label as link text.
1110
 */
1111
function theme_link_formatter_link_label($vars) {
1112
  $link_options = $vars['element'];
1113
  unset($link_options['title']);
1114
  unset($link_options['url']);
1115
  return $vars['element']['url'] ? l($vars['field']['label'], $vars['element']['url'], $link_options) : '';
1116
}
1117

    
1118
/**
1119
 * Formats a link as separate title and URL elements.
1120
 */
1121
function theme_link_formatter_link_separate($vars) {
1122
  $class = empty($vars['element']['attributes']['class']) ? '' : ' ' . $vars['element']['attributes']['class'];
1123
  unset($vars['element']['attributes']['class']);
1124
  $link_options = $vars['element'];
1125
  unset($link_options['title']);
1126
  unset($link_options['url']);
1127
  $title = empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
1128

    
1129
  // @TODO static html markup looks not very elegant
1130
  // needs smarter output solution and an optional title/url seperator
1131
  $url_parts = _link_parse_url($vars['element']['url']);
1132
  $output = '';
1133
  $output .= '<div class="link-item ' . $class . '">';
1134
  if (!empty($title)) {
1135
    $output .= '<div class="link-title">' . $title . '</div>';
1136
  }
1137
  $output .= '<div class="link-url">' . l($url_parts['url'], $vars['element']['url'], $link_options) . '</div>';
1138
  $output .= '</div>';
1139
  return $output;
1140
}
1141

    
1142
/**
1143
 * Implements hook_token_list().
1144
 *
1145
 * @TODO: hook_token_list no longer exists - this should change to hook_token_info().
1146
 */
1147
function link_token_list($type = 'all') {
1148
  if ($type === 'field' || $type === 'all') {
1149
    $tokens = array();
1150
    $tokens['link']['url'] = t("Link URL");
1151
    $tokens['link']['title'] = t("Link title");
1152
    $tokens['link']['view'] = t("Formatted html link");
1153
    return $tokens;
1154
  }
1155
}
1156

    
1157
/**
1158
 * Implements hook_token_values().
1159
 *
1160
 * @TODO: hook_token_values no longer exists - this should change to hook_tokens().
1161
 */
1162
function link_token_values($type, $object = NULL) {
1163
  if ($type === 'field') {
1164
    $item = $object[0];
1165

    
1166
    $tokens['url'] = $item['url'];
1167
    $tokens['title'] = $item['title'];
1168
    $tokens['view'] = isset($item['view']) ? $item['view'] : '';
1169

    
1170
    return $tokens;
1171
  }
1172
}
1173

    
1174
/**
1175
 * Implements hook_views_api().
1176
 */
1177
function link_views_api() {
1178
  return array(
1179
    'api' => 2,
1180
    'path' => drupal_get_path('module', 'link') . '/views',
1181
  );
1182
}
1183

    
1184
/**
1185
 * Forms a valid URL if possible from an entered address.
1186
 *
1187
 * Trims whitespace and automatically adds an http:// to addresses without a
1188
 * protocol specified
1189
 *
1190
 * @param string $url
1191
 *   The url entered by the user.
1192
 * @param string $protocol
1193
 *   The protocol to be prepended to the url if one is not specified
1194
 */
1195
function link_cleanup_url($url, $protocol = 'http') {
1196
  $url = trim($url);
1197
  $type = link_url_type($url);
1198

    
1199
  if ($type === LINK_EXTERNAL) {
1200
    // Check if there is no protocol specified.
1201
    $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
1202
    if (empty($protocol_match)) {
1203
      // But should there be? Add an automatic http:// if it starts with a domain name.
1204
      $LINK_DOMAINS = _link_domains();
1205
      $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(' . $LINK_DOMAINS . '|[a-z]{2}))/i', $url);
1206
      if (!empty($domain_match)) {
1207
        $url = $protocol . "://" . $url;
1208
      }
1209
    }
1210
  }
1211

    
1212
  return $url;
1213
}
1214

    
1215
/**
1216
 * Validates a URL.
1217
 *
1218
 * @param $text
1219
 *   Url to be validated.
1220
 *
1221
 * @param $langcode
1222
 *   An optional language code to look up the path in.
1223
 *
1224
 * @return boolean
1225
 *   True if a valid link, FALSE otherwise.
1226
 */
1227
function link_validate_url($text, $langcode = NULL) {
1228
  $text = link_cleanup_url($text);
1229
  $type = link_url_type($text);
1230

    
1231
  if ($type && ($type == LINK_INTERNAL || $type == LINK_EXTERNAL)) {
1232
    $flag = valid_url($text, TRUE);
1233
    if (!$flag) {
1234
      $normal_path = drupal_get_normal_path($text, $langcode);
1235
      $parsed_link = parse_url($normal_path, PHP_URL_PATH);
1236
      if ($normal_path != $parsed_link) {
1237
        $normal_path = $parsed_link;
1238
      }
1239
      $flag = drupal_valid_path($normal_path);
1240
    }
1241
    if (!$flag) {
1242
      $flag = file_exists($normal_path);
1243
    }
1244
    if (!$flag) {
1245
      $uri = file_build_uri($normal_path);
1246
      $flag = file_exists($uri);
1247
    }
1248
  }
1249
  else {
1250
    $flag = (bool) $type;
1251
  }
1252

    
1253
  return $flag;
1254
}
1255

    
1256
/**
1257
 * Type check a URL.
1258
 *
1259
 * Accepts all URLs following RFC 1738 standard for URL formation and all e-mail
1260
 * addresses following the RFC 2368 standard for mailto address formation.
1261
 *
1262
 * @param string $text
1263
 *   Url to be checked.
1264
 * 
1265
 * @return mixed
1266
 *   Returns boolean FALSE if the URL is not valid. On success, returns one of
1267
 *   the LINK_(linktype) constants.
1268
 */
1269
function link_url_type($text) {
1270
  // @TODO Complete letters.
1271
  $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array(
1272
    "&#x00E6;", // æ
1273
    "&#x00C6;", // Æ
1274
    "&#x00C0;", // À
1275
    "&#x00E0;", // à
1276
    "&#x00C1;", // Á
1277
    "&#x00E1;", // á
1278
    "&#x00C2;", // Â
1279
    "&#x00E2;", // â
1280
    "&#x00E5;", // å
1281
    "&#x00C5;", // Å
1282
    "&#x00E4;", // ä
1283
    "&#x00C4;", // Ä
1284
    "&#x00C7;", // Ç
1285
    "&#x00E7;", // ç
1286
    "&#x00D0;", // Ð
1287
    "&#x00F0;", // ð
1288
    "&#x00C8;", // È
1289
    "&#x00E8;", // è
1290
    "&#x00C9;", // É
1291
    "&#x00E9;", // é
1292
    "&#x00CA;", // Ê
1293
    "&#x00EA;", // ê
1294
    "&#x00CB;", // Ë
1295
    "&#x00EB;", // ë
1296
    "&#x00CE;", // Î
1297
    "&#x00EE;", // î
1298
    "&#x00CF;", // Ï
1299
    "&#x00EF;", // ï
1300
    "&#x00F8;", // ø
1301
    "&#x00D8;", // Ø
1302
    "&#x00F6;", // ö
1303
    "&#x00D6;", // Ö
1304
    "&#x00D4;", // Ô
1305
    "&#x00F4;", // ô
1306
    "&#x00D5;", // Õ
1307
    "&#x00F5;", // õ
1308
    "&#x0152;", // Œ
1309
    "&#x0153;", // œ
1310
    "&#x00FC;", // ü
1311
    "&#x00DC;", // Ü
1312
    "&#x00D9;", // Ù
1313
    "&#x00F9;", // ù
1314
    "&#x00DB;", // Û
1315
    "&#x00FB;", // û
1316
    "&#x0178;", // Ÿ
1317
    "&#x00FF;", // ÿ
1318
    "&#x00D1;", // Ñ
1319
    "&#x00F1;", // ñ
1320
    "&#x00FE;", // þ
1321
    "&#x00DE;", // Þ
1322
    "&#x00FD;", // ý
1323
    "&#x00DD;", // Ý
1324
    "&#x00BF;", // ¿
1325
  )), ENT_QUOTES, 'UTF-8');
1326

    
1327
  $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
1328
    "&#x00DF;", // ß
1329
  )), ENT_QUOTES, 'UTF-8');
1330
  $allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
1331
  $LINK_DOMAINS = _link_domains();
1332

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

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

    
1344
  // Pattern specific to internal links.
1345
  $internal_pattern = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\] ]+)";
1346
  $internal_pattern_file = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)]+)$/i";
1347

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

    
1353
  // The rest of the path for a standard URL.
1354
  $end = $directories . '?' . $query . '?' . $anchor . '?' . '$/i';
1355

    
1356
  $message_id = '[^@].*@' . $domain;
1357
  $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
1358
  $news_pattern = '/^news:(' . $newsgroup_name . '|' . $message_id . ')$/i';
1359

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

    
1363
  if (strpos($text, '<front>') === 0) {
1364
    return LINK_FRONT;
1365
  }
1366
  if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
1367
    return LINK_EMAIL;
1368
  }
1369
  if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
1370
    return LINK_NEWS;
1371
  }
1372
  if (preg_match($internal_pattern . $end, $text)) {
1373
    return LINK_INTERNAL;
1374
  }
1375
  if (preg_match($external_pattern . $end, $text)) {
1376
    return LINK_EXTERNAL;
1377
  }
1378
  if (preg_match($internal_pattern_file, $text)) {
1379
    return LINK_INTERNAL;
1380
  }
1381

    
1382
  return FALSE;
1383
}
1384

    
1385
/**
1386
 * Returns the list of allowed domains, including domains added by admins via variable_set/$config.
1387
 */
1388
function _link_domains() {
1389
  $link_extra_domains = variable_get('link_extra_domains', array());
1390
  return empty($link_extra_domains) ? LINK_DOMAINS : LINK_DOMAINS . '|' . implode('|', $link_extra_domains);
1391
}
1392

    
1393
/**
1394
 * Implements hook_migrate_field_alter().
1395
 */
1396
function link_content_migrate_field_alter(&$field_value, $instance_value) {
1397
  if ($field_value['type'] == 'link') {
1398
    // Adjust the field type.
1399
    $field_value['type'] = 'link_field';
1400
    // Remove settings that are now on the instance.
1401
    foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
1402
      unset($field_value['settings'][$setting]);
1403
    }
1404
  }
1405
}
1406

    
1407
/**
1408
 * Implements hook_migrate_instance_alter().
1409
 *
1410
 * Widget type also changed to link_field.
1411
 */
1412
function link_content_migrate_instance_alter(&$instance_value, $field_value) {
1413
  if ($field_value['type'] == 'link') {
1414
    // Grab settings that were previously on the field.
1415
    foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
1416
      if (isset($field_value['settings'][$setting])) {
1417
        $instance_value['settings'][$setting] = $field_value['settings'][$setting];
1418
      }
1419
    }
1420
    // Adjust widget type.
1421
    if ($instance_value['widget']['type'] == 'link') {
1422
      $instance_value['widget']['type'] = 'link_field';
1423
    }
1424
    // Adjust formatter types.
1425
    foreach ($instance_value['display'] as $context => $settings) {
1426
      if (in_array($settings['type'], array('default', 'title_plain', 'url', 'plain', 'short', 'label', 'separate'))) {
1427
        $instance_value['display'][$context]['type'] = 'link_' . $settings['type'];
1428
      }
1429
    }
1430
  }
1431
}
1432

    
1433
/**
1434
 * Implements hook_field_settings_form().
1435
 */
1436
function link_field_settings_form() {
1437
  return array();
1438
}
1439

    
1440
/**
1441
 * Additional callback to adapt the property info of link fields.
1442
 * 
1443
 * @see entity_metadata_field_entity_property_info()
1444
 */
1445
function link_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
1446
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
1447
  // Define a data structure so it's possible to deal with both the link title
1448
  // and URL.
1449
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
1450
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
1451

    
1452
  // Auto-create the field item as soon as a property is set.
1453
  $property['auto creation'] = 'link_field_item_create';
1454

    
1455
  $property['property info'] = link_field_item_property_info();
1456
  $property['property info']['url']['required'] = !$instance['settings']['url'];
1457
  $property['property info']['title']['required'] = ($instance['settings']['title'] == 'required');
1458
  if ($instance['settings']['title'] == 'none') {
1459
    unset($property['property info']['title']);
1460
  }
1461
  unset($property['query callback']);
1462
}
1463

    
1464
/**
1465
 * Callback for creating a new, empty link field item.
1466
 *
1467
 * @see link_field_property_info_callback()
1468
 */
1469
function link_field_item_create() {
1470
  return array('title' => NULL, 'url' => NULL);
1471
}
1472

    
1473
/**
1474
 * Defines info for the properties of the link-field item data structure.
1475
 */
1476
function link_field_item_property_info() {
1477
  $properties['title'] = array(
1478
    'type' => 'text',
1479
    'label' => t('The title of the link.'),
1480
    'setter callback' => 'entity_property_verbatim_set',
1481
  );
1482
  $properties['url'] = array(
1483
    'type' => 'uri',
1484
    'label' => t('The URL of the link.'),
1485
    'setter callback' => 'entity_property_verbatim_set',
1486
  );
1487
  $properties['attributes'] = array(
1488
    'type' => 'struct',
1489
    'label' => t('The attributes of the link.'),
1490
    'setter callback' => 'entity_property_verbatim_set',
1491
    'getter callback' => 'link_attribute_property_get',
1492
  );
1493
  return $properties;
1494
}
1495

    
1496
/**
1497
 * Entity property info getter callback for link attributes.
1498
 */
1499
function link_attribute_property_get($data, array $options, $name, $type, $info) {
1500
  return isset($data[$name]) ? array_filter($data[$name]) : array();
1501
}
1502

    
1503
/**
1504
 * Implements hook_field_update_instance().
1505
 */
1506
function link_field_update_instance($instance, $prior_instance) {
1507
  if (function_exists('i18n_string_update') && $instance['widget']['type'] == 'link_field' && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {
1508
    $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
1509
    i18n_string_update($i18n_string_name, $instance['settings']['title_value']);
1510
  }
1511
}
1512

    
1513
/**
1514
 * Implements hook_i18n_string_list_TEXTGROUP_alter().
1515
 */
1516
function link_i18n_string_list_field_alter(&$strings, $type = NULL, $object = NULL) {
1517
  if ($type != 'field_instance' || !is_array($object) || !isset($object['widget']['type'])) {
1518
    return;
1519
  }
1520
  if ($object['widget']['type'] == 'link_field' && isset($object['settings']['title_value'])) {
1521
    $strings['field'][$object['field_name']][$object['bundle']]['title_value']['string'] = $object['settings']['title_value'];
1522
  }
1523
}