link.module 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. <?php
  2. /**
  3. * @file
  4. * Defines simple link field types.
  5. */
  6. define('LINK_EXTERNAL', 'external');
  7. define('LINK_INTERNAL', 'internal');
  8. define('LINK_FRONT', 'front');
  9. define('LINK_EMAIL', 'email');
  10. define('LINK_NEWS', 'news');
  11. 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');
  12. define('LINK_TARGET_DEFAULT', 'default');
  13. define('LINK_TARGET_NEW_WINDOW', '_blank');
  14. define('LINK_TARGET_TOP', '_top');
  15. define('LINK_TARGET_USER', 'user');
  16. /**
  17. * Maximum URLs length - needs to match value in link.install.
  18. */
  19. define('LINK_URL_MAX_LENGTH', 2048);
  20. /**
  21. * Implements hook_field_info().
  22. */
  23. function link_field_info() {
  24. return array(
  25. 'link_field' => array(
  26. 'label' => t('Link'),
  27. 'description' => t('Store a title, href, and attributes in the database to assemble a link.'),
  28. 'settings' => array(
  29. 'attributes' => _link_default_attributes(),
  30. 'url' => 0,
  31. 'title' => 'optional',
  32. 'title_value' => '',
  33. 'title_maxlength' => 128,
  34. 'enable_tokens' => 1,
  35. 'display' => array(
  36. 'url_cutoff' => 80,
  37. ),
  38. ),
  39. 'instance_settings' => array(
  40. 'attributes' => _link_default_attributes(),
  41. 'url' => 0,
  42. 'title' => 'optional',
  43. 'title_value' => '',
  44. 'title_label_use_field_label' => FALSE,
  45. 'title_maxlength' => 128,
  46. 'enable_tokens' => 1,
  47. 'display' => array(
  48. 'url_cutoff' => 80,
  49. ),
  50. 'validate_url' => 1,
  51. 'absolute_url' => 1,
  52. ),
  53. 'default_widget' => 'link_field',
  54. 'default_formatter' => 'link_default',
  55. // Support hook_entity_property_info() from contrib "Entity API".
  56. 'property_type' => 'field_item_link',
  57. 'property_callbacks' => array('link_field_property_info_callback'),
  58. ),
  59. );
  60. }
  61. /**
  62. * Implements hook_field_instance_settings_form().
  63. */
  64. function link_field_instance_settings_form($field, $instance) {
  65. $form = array(
  66. '#element_validate' => array('link_field_settings_form_validate'),
  67. );
  68. $form['absolute_url'] = array(
  69. '#type' => 'checkbox',
  70. '#title' => t('Absolute URL'),
  71. '#default_value' => isset($instance['settings']['absolute_url']) && ($instance['settings']['absolute_url'] !== '') ? $instance['settings']['absolute_url'] : TRUE,
  72. '#description' => t('If checked, the URL will always render as an absolute URL.'),
  73. );
  74. $form['validate_url'] = array(
  75. '#type' => 'checkbox',
  76. '#title' => t('Validate URL'),
  77. '#default_value' => isset($instance['settings']['validate_url']) && ($instance['settings']['validate_url'] !== '') ? $instance['settings']['validate_url'] : TRUE,
  78. '#description' => t('If checked, the URL field will be verified as a valid URL during validation.'),
  79. );
  80. $form['url'] = array(
  81. '#type' => 'checkbox',
  82. '#title' => t('Optional URL'),
  83. '#default_value' => isset($instance['settings']['url']) ? $instance['settings']['url'] : '',
  84. '#return_value' => 'optional',
  85. '#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.'),
  86. );
  87. $title_options = array(
  88. 'optional' => t('Optional Title'),
  89. 'required' => t('Required Title'),
  90. 'value' => t('Static Title'),
  91. 'none' => t('No Title'),
  92. );
  93. $form['title'] = array(
  94. '#type' => 'radios',
  95. '#title' => t('Link Title'),
  96. '#default_value' => isset($instance['settings']['title']) ? $instance['settings']['title'] : 'optional',
  97. '#options' => $title_options,
  98. '#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.'),
  99. );
  100. $form['title_value'] = array(
  101. '#type' => 'textfield',
  102. '#title' => t('Static title'),
  103. '#default_value' => isset($instance['settings']['title_value']) ? $instance['settings']['title_value'] : '',
  104. '#description' => t('This title will always be used if &ldquo;Static Title&rdquo; is selected above.'),
  105. );
  106. $form['title_label_use_field_label'] = array(
  107. '#type' => 'checkbox',
  108. '#title' => t('Use field label as the label for the title field'),
  109. '#default_value' => isset($instance['settings']['title_label_use_field_label']) ? $instance['settings']['title_label_use_field_label'] : FALSE,
  110. '#description' => t('If this is checked the field label will be hidden.'),
  111. );
  112. $form['title_maxlength'] = array(
  113. '#type' => 'textfield',
  114. '#title' => t('Max length of title field'),
  115. '#default_value' => isset($instance['settings']['title_maxlength']) ? $instance['settings']['title_maxlength'] : '128',
  116. '#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.'),
  117. '#maxlength' => 3,
  118. '#size' => 3,
  119. );
  120. if (module_exists('token')) {
  121. // Add token module replacements fields.
  122. $form['enable_tokens'] = array(
  123. '#type' => 'checkbox',
  124. '#title' => t('Allow user-entered tokens'),
  125. '#default_value' => isset($instance['settings']['enable_tokens']) ? $instance['settings']['enable_tokens'] : 1,
  126. '#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.'),
  127. );
  128. $entity_info = entity_get_info($instance['entity_type']);
  129. $form['tokens_help'] = array(
  130. '#theme' => 'token_tree',
  131. '#token_types' => array($entity_info['token type']),
  132. '#global_types' => TRUE,
  133. '#click_insert' => TRUE,
  134. '#dialog' => TRUE,
  135. );
  136. }
  137. $form['display'] = array(
  138. '#tree' => TRUE,
  139. );
  140. $form['display']['url_cutoff'] = array(
  141. '#type' => 'textfield',
  142. '#title' => t('URL Display Cutoff'),
  143. '#default_value' => isset($instance['settings']['display']['url_cutoff']) ? $instance['settings']['display']['url_cutoff'] : '80',
  144. '#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.'),
  145. '#maxlength' => 3,
  146. '#size' => 3,
  147. );
  148. $target_options = array(
  149. LINK_TARGET_DEFAULT => t('Default (no target attribute)'),
  150. LINK_TARGET_TOP => t('Open link in window root'),
  151. LINK_TARGET_NEW_WINDOW => t('Open link in new window'),
  152. LINK_TARGET_USER => t('Allow the user to choose'),
  153. );
  154. $form['attributes'] = array(
  155. '#tree' => TRUE,
  156. );
  157. $form['attributes']['target'] = array(
  158. '#type' => 'radios',
  159. '#title' => t('Link Target'),
  160. '#default_value' => empty($instance['settings']['attributes']['target']) ? LINK_TARGET_DEFAULT : $instance['settings']['attributes']['target'],
  161. '#options' => $target_options,
  162. );
  163. $form['attributes']['rel'] = array(
  164. '#type' => 'textfield',
  165. '#title' => t('Rel Attribute'),
  166. '#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.'),
  167. '#default_value' => empty($instance['settings']['attributes']['rel']) ? '' : $instance['settings']['attributes']['rel'],
  168. '#field_prefix' => 'rel = "',
  169. '#field_suffix' => '"',
  170. '#size' => 20,
  171. );
  172. $rel_remove_options = array(
  173. 'default' => t('Keep rel as set up above (untouched/default)'),
  174. 'rel_remove_external' => t('Remove rel if given link is external'),
  175. 'rel_remove_internal' => t('Remove rel if given link is internal'),
  176. );
  177. $form['rel_remove'] = array(
  178. '#type' => 'radios',
  179. '#title' => t('Remove rel attribute automatically'),
  180. '#default_value' => !isset($instance['settings']['rel_remove']) ? 'default' : $instance['settings']['rel_remove'],
  181. '#description' => t('Turn on/off if rel attribute should be removed automatically, if user given link is internal/external'),
  182. '#options' => $rel_remove_options,
  183. );
  184. $form['attributes']['configurable_class'] = array(
  185. '#title' => t("Allow the user to enter a custom link class per link"),
  186. '#type' => 'checkbox',
  187. '#default_value' => empty($instance['settings']['attributes']['configurable_class']) ? '' : $instance['settings']['attributes']['configurable_class'],
  188. );
  189. $form['attributes']['class'] = array(
  190. '#type' => 'textfield',
  191. '#title' => t('Additional CSS Class'),
  192. '#description' => t('When output, this link will have this class attribute. Multiple classes should be separated by spaces.'),
  193. '#default_value' => empty($instance['settings']['attributes']['class']) ? '' : $instance['settings']['attributes']['class'],
  194. );
  195. $form['attributes']['configurable_title'] = array(
  196. '#title' => t("Allow the user to enter a link 'title' attribute"),
  197. '#type' => 'checkbox',
  198. '#default_value' => empty($instance['settings']['attributes']['configurable_title']) ? '' : $instance['settings']['attributes']['configurable_title'],
  199. );
  200. $form['attributes']['title'] = array(
  201. '#title' => t("Default link 'title' Attribute"),
  202. '#type' => 'textfield',
  203. '#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.'),
  204. '#default_value' => empty($instance['settings']['attributes']['title']) ? '' : $instance['settings']['attributes']['title'],
  205. '#field_prefix' => 'title = "',
  206. '#field_suffix' => '"',
  207. '#size' => 20,
  208. );
  209. return $form;
  210. }
  211. /**
  212. * #element_validate handler for link_field_instance_settings_form().
  213. */
  214. function link_field_settings_form_validate($element, &$form_state, $complete_form) {
  215. if ($form_state['values']['instance']['settings']['title'] === 'value' && empty($form_state['values']['instance']['settings']['title_value'])) {
  216. form_set_error('title_value', t('A default title must be provided if the title is a static value.'));
  217. }
  218. if (!empty($form_state['values']['instance']['settings']['display']['url_cutoff']) && !is_numeric($form_state['values']['instance']['settings']['display']['url_cutoff'])) {
  219. form_set_error('display', t('URL Display Cutoff value must be numeric.'));
  220. }
  221. if (empty($form_state['values']['instance']['settings']['title_maxlength'])) {
  222. form_set_value($element['title_maxlength'], '128', $form_state);
  223. }
  224. elseif (!is_numeric($form_state['values']['instance']['settings']['title_maxlength'])) {
  225. form_set_error('title_maxlength', t('The max length of the link title must be numeric.'));
  226. }
  227. elseif ($form_state['values']['instance']['settings']['title_maxlength'] > 255) {
  228. form_set_error('title_maxlength', t('The max length of the link title cannot be greater than 255 characters.'));
  229. }
  230. }
  231. /**
  232. * Implements hook_field_is_empty().
  233. */
  234. function link_field_is_empty($item, $field) {
  235. return empty($item['title']) && empty($item['url']);
  236. }
  237. /**
  238. * Implements hook_field_load().
  239. */
  240. function link_field_load($entity_type, $entities, $field, $instances, $langcode, &$items, $age) {
  241. foreach ($entities as $id => $entity) {
  242. foreach ($items[$id] as $delta => $item) {
  243. $items[$id][$delta]['attributes'] = _link_load($field, $item, $instances[$id]);
  244. }
  245. }
  246. }
  247. /**
  248. * Implements hook_field_validate().
  249. */
  250. function link_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  251. $optional_field_found = FALSE;
  252. if ($instance['settings']['validate_url'] !== 0 || is_null($instance['settings']['validate_url']) || !isset($instance['settings']['validate_url'])) {
  253. foreach ($items as $delta => $value) {
  254. _link_validate($items[$delta], $delta, $field, $entity, $instance, $langcode, $optional_field_found, $errors);
  255. }
  256. }
  257. if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional' && $instance['required'] && !$optional_field_found) {
  258. $errors[$field['field_name']][$langcode][0][] = array(
  259. 'error' => 'link_required',
  260. 'message' => t('At least one title or URL must be entered.'),
  261. 'error_element' => array('url' => FALSE, 'title' => TRUE),
  262. );
  263. }
  264. }
  265. /**
  266. * Implements hook_field_insert().
  267. */
  268. function link_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
  269. foreach ($items as $delta => $value) {
  270. _link_process($items[$delta], $delta, $field, $entity);
  271. }
  272. }
  273. /**
  274. * Implements hook_field_update().
  275. */
  276. function link_field_update($entity_type, $entity, $field, $instance, $langcode, &$items) {
  277. foreach ($items as $delta => $value) {
  278. _link_process($items[$delta], $delta, $field, $entity);
  279. }
  280. }
  281. /**
  282. * Implements hook_field_prepare_view().
  283. */
  284. function link_field_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items) {
  285. foreach ($items as $entity_id => $entity_items) {
  286. foreach ($entity_items as $delta => $value) {
  287. _link_sanitize($items[$entity_id][$delta], $delta, $field, $instances[$entity_id], $entities[$entity_id]);
  288. }
  289. }
  290. }
  291. /**
  292. * Implements hook_field_widget_info().
  293. */
  294. function link_field_widget_info() {
  295. return array(
  296. 'link_field' => array(
  297. 'label' => 'Link',
  298. 'field types' => array('link_field'),
  299. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  300. ),
  301. );
  302. }
  303. /**
  304. * Implements hook_field_widget_form().
  305. */
  306. function link_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  307. $element += array(
  308. '#type' => $instance['widget']['type'],
  309. '#default_value' => isset($items[$delta]) ? $items[$delta] : '',
  310. );
  311. return $element;
  312. }
  313. /**
  314. * Implements hook_field_widget_error().
  315. */
  316. function link_field_widget_error($element, $error, $form, &$form_state) {
  317. if ($error['error_element']['title']) {
  318. form_error($element['title'], $error['message']);
  319. }
  320. elseif ($error['error_element']['url']) {
  321. form_error($element['url'], $error['message']);
  322. }
  323. }
  324. /**
  325. * Unpacks the item attributes for use.
  326. */
  327. function _link_load($field, $item, $instance) {
  328. if (isset($item['attributes'])) {
  329. if (!is_array($item['attributes'])) {
  330. $item['attributes'] = unserialize($item['attributes']);
  331. }
  332. return $item['attributes'];
  333. }
  334. elseif (isset($instance['settings']['attributes'])) {
  335. return $instance['settings']['attributes'];
  336. }
  337. else {
  338. return $field['settings']['attributes'];
  339. }
  340. }
  341. /**
  342. * Prepares the item attributes and url for storage.
  343. */
  344. function _link_process(&$item, $delta, $field, $entity) {
  345. // Trim whitespace from URL.
  346. if (!empty($item['url'])) {
  347. $item['url'] = trim($item['url']);
  348. }
  349. // If no attributes are set then make sure $item['attributes'] is an empty
  350. // array, so $field['attributes'] can override it.
  351. if (empty($item['attributes'])) {
  352. $item['attributes'] = array();
  353. }
  354. // Serialize the attributes array.
  355. if (!is_string($item['attributes'])) {
  356. $item['attributes'] = serialize($item['attributes']);
  357. }
  358. // Don't save an invalid default value (e.g. 'http://').
  359. if ((isset($field['widget']['default_value'][$delta]['url']) && $item['url'] == $field['widget']['default_value'][$delta]['url']) && is_object($entity)) {
  360. if (!link_validate_url($item['url'])) {
  361. unset($item['url']);
  362. }
  363. }
  364. }
  365. /**
  366. * Validates that the link field has been entered properly.
  367. */
  368. function _link_validate(&$item, $delta, $field, $entity, $instance, $langcode, &$optional_field_found, &$errors) {
  369. if ($item['url'] && !(isset($instance['default_value'][$delta]['url']) && $item['url'] === $instance['default_value'][$delta]['url'] && !$instance['required'])) {
  370. // Validate the link.
  371. if (link_validate_url(trim($item['url'])) == FALSE) {
  372. $errors[$field['field_name']][$langcode][$delta][] = array(
  373. 'error' => 'link_required',
  374. 'message' => t('The value %value provided for %field is not a valid URL.', array(
  375. '%value' => trim($item['url']),
  376. '%field' => $instance['label'],
  377. )),
  378. 'error_element' => array('url' => TRUE, 'title' => FALSE),
  379. );
  380. }
  381. // Require a title for the link if necessary.
  382. if ($instance['settings']['title'] == 'required' && strlen(trim($item['title'])) == 0) {
  383. $errors[$field['field_name']][$langcode][$delta][] = array(
  384. 'error' => 'link_required',
  385. 'message' => t('Titles are required for all links.'),
  386. 'error_element' => array('url' => FALSE, 'title' => TRUE),
  387. );
  388. }
  389. }
  390. // Require a link if we have a title.
  391. if ($instance['settings']['url'] !== 'optional' && strlen(isset($item['title']) ? $item['title'] : NULL) > 0 && strlen(trim($item['url'])) == 0) {
  392. $errors[$field['field_name']][$langcode][$delta][] = array(
  393. 'error' => 'link_required',
  394. 'message' => t('You cannot enter a title without a link url.'),
  395. 'error_element' => array('url' => TRUE, 'title' => FALSE),
  396. );
  397. }
  398. // In a totally bizzaro case, where URLs and titles are optional but the field is required, ensure there is at least one link.
  399. if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional'
  400. && (strlen(trim($item['url'])) !== 0 || strlen(trim($item['title'])) !== 0)) {
  401. $optional_field_found = TRUE;
  402. }
  403. // Require entire field.
  404. if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional' && $instance['required'] == 1 && !$optional_field_found && isset($instance['id'])) {
  405. $errors[$field['field_name']][$langcode][$delta][] = array(
  406. 'error' => 'link_required',
  407. 'message' => t('At least one title or URL must be entered.'),
  408. 'error_element' => array('url' => FALSE, 'title' => TRUE),
  409. );
  410. }
  411. }
  412. /**
  413. * Clean up user-entered values for a link field according to field settings.
  414. *
  415. * @param array $item
  416. * A single link item, usually containing url, title, and attributes.
  417. * @param int $delta
  418. * The delta value if this field is one of multiple fields.
  419. * @param array $field
  420. * The CCK field definition.
  421. * @param object $entity
  422. * The entity containing this link.
  423. */
  424. function _link_sanitize(&$item, $delta, &$field, $instance, &$entity) {
  425. // Don't try to process empty links.
  426. if (empty($item['url']) && empty($item['title'])) {
  427. return;
  428. }
  429. if (empty($item['html'])) {
  430. $item['html'] = FALSE;
  431. }
  432. // Replace URL tokens.
  433. $entity_type = $instance['entity_type'];
  434. $entity_info = entity_get_info($entity_type);
  435. $property_id = $entity_info['entity keys']['id'];
  436. $entity_token_type = isset($entity_info['token type']) ? $entity_info['token type'] : (
  437. $entity_type == 'taxonomy_term' || $entity_type == 'taxonomy_vocabulary' ? str_replace('taxonomy_', '', $entity_type) : $entity_type
  438. );
  439. if (isset($instance['settings']['enable_tokens']) && $instance['settings']['enable_tokens']) {
  440. global $user;
  441. // Load the entity if necessary for entities in views.
  442. if (isset($entity->{$property_id})) {
  443. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  444. $entity_loaded = array_pop($entity_loaded);
  445. }
  446. else {
  447. $entity_loaded = $entity;
  448. }
  449. $item['url'] = token_replace($item['url'], array($entity_token_type => $entity_loaded));
  450. }
  451. $type = link_validate_url($item['url']);
  452. // If the type of the URL cannot be determined and URL validation is disabled,
  453. // then assume LINK_EXTERNAL for later processing.
  454. if ($type == FALSE && $instance['settings']['validate_url'] === 0) {
  455. $type = LINK_EXTERNAL;
  456. }
  457. $url = link_cleanup_url($item['url']);
  458. $url_parts = _link_parse_url($url);
  459. if (!empty($url_parts['url'])) {
  460. $item['url'] = $url_parts['url'];
  461. $item += array(
  462. 'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
  463. 'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
  464. 'absolute' => !empty($instance['settings']['absolute_url']),
  465. 'html' => TRUE,
  466. );
  467. }
  468. // Create a shortened URL for display.
  469. if ($type == LINK_EMAIL) {
  470. $display_url = str_replace('mailto:', '', $url);
  471. }
  472. else {
  473. $display_url = url($url_parts['url'],
  474. array(
  475. 'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
  476. 'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
  477. 'absolute' => !empty($instance['settings']['absolute_url']),
  478. )
  479. );
  480. }
  481. if ($instance['settings']['display']['url_cutoff'] && strlen($display_url) > $instance['settings']['display']['url_cutoff']) {
  482. $display_url = substr($display_url, 0, $instance['settings']['display']['url_cutoff']) . "...";
  483. }
  484. $item['display_url'] = $display_url;
  485. // Use the title defined at the instance level.
  486. if ($instance['settings']['title'] == 'value' && strlen(trim($instance['settings']['title_value']))) {
  487. $title = $instance['settings']['title_value'];
  488. if (function_exists('i18n_string_translate')) {
  489. $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
  490. $title = i18n_string_translate($i18n_string_name, $title);
  491. }
  492. }
  493. // Use the title defined by the user at the widget level.
  494. elseif (isset($item['title'])) {
  495. $title = $item['title'];
  496. }
  497. else {
  498. $title = '';
  499. }
  500. // Replace title tokens.
  501. if ($title && ($instance['settings']['title'] == 'value' || $instance['settings']['enable_tokens'])) {
  502. // Load the entity if necessary for entities in views.
  503. if (isset($entity->{$property_id})) {
  504. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  505. $entity_loaded = array_pop($entity_loaded);
  506. }
  507. else {
  508. $entity_loaded = $entity;
  509. }
  510. $title = token_replace($title, array($entity_token_type => $entity_loaded));
  511. $title = filter_xss($title, array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
  512. $item['html'] = TRUE;
  513. }
  514. $item['title'] = empty($title) ? $item['display_url'] : $title;
  515. if (!isset($item['attributes'])) {
  516. $item['attributes'] = array();
  517. }
  518. // Unserialize attributtes array if it has not been unserialized yet.
  519. if (!is_array($item['attributes'])) {
  520. $item['attributes'] = (array) unserialize($item['attributes']);
  521. }
  522. // Add default attributes.
  523. if (!is_array($instance['settings']['attributes'])) {
  524. $instance['settings']['attributes'] = _link_default_attributes();
  525. }
  526. else {
  527. $instance['settings']['attributes'] += _link_default_attributes();
  528. }
  529. // Merge item attributes with attributes defined at the field level.
  530. $item['attributes'] += $instance['settings']['attributes'];
  531. // If user is not allowed to choose target attribute, use default defined at
  532. // field level.
  533. if ($instance['settings']['attributes']['target'] != LINK_TARGET_USER) {
  534. $item['attributes']['target'] = $instance['settings']['attributes']['target'];
  535. }
  536. elseif ($item['attributes']['target'] == LINK_TARGET_USER) {
  537. $item['attributes']['target'] = LINK_TARGET_DEFAULT;
  538. }
  539. // Remove the target attribute if the default (no target) is selected.
  540. if (empty($item['attributes']) || (isset($item['attributes']['target']) && $item['attributes']['target'] == LINK_TARGET_DEFAULT)) {
  541. unset($item['attributes']['target']);
  542. }
  543. // Remove rel attribute for internal or external links if selected.
  544. if (isset($item['attributes']['rel']) && isset($instance['settings']['rel_remove']) && $instance['settings']['rel_remove'] != 'default') {
  545. if (($instance['settings']['rel_remove'] != 'rel_remove_internal' && $type != LINK_INTERNAL) ||
  546. ($instance['settings']['rel_remove'] != 'rel_remove_external' && $type != LINK_EXTERNAL)) {
  547. unset($item['attributes']['rel']);
  548. }
  549. }
  550. // Handle "title" link attribute.
  551. if (!empty($item['attributes']['title']) && module_exists('token')) {
  552. // Load the entity (necessary for entities in views).
  553. if (isset($entity->{$property_id})) {
  554. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  555. $entity_loaded = array_pop($entity_loaded);
  556. }
  557. else {
  558. $entity_loaded = $entity;
  559. }
  560. $item['attributes']['title'] = token_replace($item['attributes']['title'], array($entity_token_type => $entity_loaded));
  561. $item['attributes']['title'] = filter_xss($item['attributes']['title'], array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
  562. }
  563. // Handle attribute classes.
  564. if (!empty($item['attributes']['class'])) {
  565. $classes = explode(' ', $item['attributes']['class']);
  566. foreach ($classes as &$class) {
  567. $class = drupal_html_class($class);
  568. }
  569. $item['attributes']['class'] = implode(' ', $classes);
  570. }
  571. unset($item['attributes']['configurable_class']);
  572. // Remove title attribute if it's equal to link text.
  573. if (isset($item['attributes']['title']) && $item['attributes']['title'] == $item['title']) {
  574. unset($item['attributes']['title']);
  575. }
  576. unset($item['attributes']['configurable_title']);
  577. // Remove empty attributes.
  578. $item['attributes'] = array_filter($item['attributes']);
  579. }
  580. /**
  581. * Because parse_url doesn't work with relative urls.
  582. *
  583. * @param string $url
  584. * URL to parse.
  585. *
  586. * @return array
  587. * Array of url pieces - only 'url', 'query', and 'fragment'.
  588. */
  589. function _link_parse_url($url) {
  590. $url_parts = array();
  591. // Separate out the anchor, if any.
  592. if (strpos($url, '#') !== FALSE) {
  593. $url_parts['fragment'] = substr($url, strpos($url, '#') + 1);
  594. $url = substr($url, 0, strpos($url, '#'));
  595. }
  596. // Separate out the query string, if any.
  597. if (strpos($url, '?') !== FALSE) {
  598. $query = substr($url, strpos($url, '?') + 1);
  599. $url_parts['query'] = _link_parse_str($query);
  600. $url = substr($url, 0, strpos($url, '?'));
  601. }
  602. $url_parts['url'] = $url;
  603. return $url_parts;
  604. }
  605. /**
  606. * Replaces the PHP parse_str() function.
  607. *
  608. * Because parse_str replaces the following characters in query parameters name
  609. * in order to maintain compability with deprecated register_globals directive:
  610. *
  611. * - chr(32) ( ) (space)
  612. * - chr(46) (.) (dot)
  613. * - chr(91) ([) (open square bracket)
  614. * - chr(128) - chr(159) (various)
  615. *
  616. * @param string $query
  617. * Query to parse.
  618. *
  619. * @return array
  620. * Array of query parameters.
  621. *
  622. * @see http://php.net/manual/en/language.variables.external.php#81080
  623. */
  624. function _link_parse_str($query) {
  625. $query_array = array();
  626. $pairs = explode('&', $query);
  627. foreach ($pairs as $pair) {
  628. $name_value = explode('=', $pair, 2);
  629. $name = urldecode($name_value[0]);
  630. $value = isset($name_value[1]) ? urldecode($name_value[1]) : NULL;
  631. $query_array[$name] = $value;
  632. }
  633. return $query_array;
  634. }
  635. /**
  636. * Implements hook_theme().
  637. */
  638. function link_theme() {
  639. return array(
  640. 'link_formatter_link_default' => array(
  641. 'variables' => array('element' => NULL, 'field' => NULL),
  642. ),
  643. 'link_formatter_link_plain' => array(
  644. 'variables' => array('element' => NULL, 'field' => NULL),
  645. ),
  646. 'link_formatter_link_absolute' => array(
  647. 'variables' => array('element' => NULL, 'field' => NULL),
  648. ),
  649. 'link_formatter_link_domain' => array(
  650. 'variables' => array('element' => NULL, 'display' => NULL, 'field' => NULL),
  651. ),
  652. 'link_formatter_link_title_plain' => array(
  653. 'variables' => array('element' => NULL, 'field' => NULL),
  654. ),
  655. 'link_formatter_link_url' => array(
  656. 'variables' => array('element' => NULL, 'field' => NULL),
  657. ),
  658. 'link_formatter_link_short' => array(
  659. 'variables' => array('element' => NULL, 'field' => NULL),
  660. ),
  661. 'link_formatter_link_label' => array(
  662. 'variables' => array('element' => NULL, 'field' => NULL),
  663. ),
  664. 'link_formatter_link_separate' => array(
  665. 'variables' => array('element' => NULL, 'field' => NULL),
  666. ),
  667. 'link_field' => array(
  668. 'render element' => 'element',
  669. ),
  670. );
  671. }
  672. /**
  673. * Formats a link field widget.
  674. */
  675. function theme_link_field($vars) {
  676. drupal_add_css(drupal_get_path('module', 'link') . '/link.css');
  677. $element = $vars['element'];
  678. // Prefix single value link fields with the name of the field.
  679. if (empty($element['#field']['multiple'])) {
  680. if (isset($element['url']) && !isset($element['title'])) {
  681. $element['url']['#title_display'] = 'invisible';
  682. }
  683. }
  684. $output = '';
  685. $output .= '<div class="link-field-subrow clearfix">';
  686. if (isset($element['title'])) {
  687. $output .= '<div class="link-field-title link-field-column">' . drupal_render($element['title']) . '</div>';
  688. }
  689. $output .= '<div class="link-field-url' . (isset($element['title']) ? ' link-field-column' : '') . '">' . drupal_render($element['url']) . '</div>';
  690. $output .= '</div>';
  691. if (!empty($element['attributes']['target'])) {
  692. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['target']) . '</div>';
  693. }
  694. if (!empty($element['attributes']['title'])) {
  695. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['title']) . '</div>';
  696. }
  697. if (!empty($element['attributes']['class'])) {
  698. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['class']) . '</div>';
  699. }
  700. $output .= drupal_render_children($element);
  701. return $output;
  702. }
  703. /**
  704. * Implements hook_element_info().
  705. */
  706. function link_element_info() {
  707. $elements = array();
  708. $elements['link_field'] = array(
  709. '#input' => TRUE,
  710. '#process' => array('link_field_process'),
  711. '#theme' => 'link_field',
  712. '#theme_wrappers' => array('form_element'),
  713. );
  714. return $elements;
  715. }
  716. /**
  717. * Returns the default attributes and their values.
  718. */
  719. function _link_default_attributes() {
  720. return array(
  721. 'target' => LINK_TARGET_DEFAULT,
  722. 'class' => '',
  723. 'rel' => '',
  724. );
  725. }
  726. /**
  727. * Processes the link type element before displaying the field.
  728. *
  729. * Build the form element. When creating a form using FAPI #process,
  730. * note that $element['#value'] is already set.
  731. *
  732. * The $fields array is in $complete_form['#field_info'][$element['#field_name']].
  733. */
  734. function link_field_process($element, $form_state, $complete_form) {
  735. $instance = field_widget_instance($element, $form_state);
  736. $settings = $instance['settings'];
  737. $element['url'] = array(
  738. '#type' => 'textfield',
  739. '#maxlength' => LINK_URL_MAX_LENGTH,
  740. '#title' => t('URL'),
  741. '#required' => ($element['#delta'] == 0 && $settings['url'] !== 'optional') ? $element['#required'] : FALSE,
  742. '#default_value' => isset($element['#value']['url']) ? $element['#value']['url'] : NULL,
  743. );
  744. if ($settings['title'] !== 'none' && $settings['title'] !== 'value') {
  745. // Figure out the label of the title field.
  746. if (!empty($settings['title_label_use_field_label'])) {
  747. // Use the element label as the title field label.
  748. $title_label = $element['#title'];
  749. // Hide the field label because there is no need for the duplicate labels.
  750. $element['#title_display'] = 'invisible';
  751. }
  752. else {
  753. $title_label = t('Title');
  754. }
  755. $element['title'] = array(
  756. '#type' => 'textfield',
  757. '#maxlength' => $settings['title_maxlength'],
  758. '#title' => $title_label,
  759. '#description' => t('The link title is limited to @maxlength characters maximum.', array('@maxlength' => $settings['title_maxlength'])),
  760. '#required' => ($settings['title'] == 'required' && (($element['#delta'] == 0 && $element['#required']) || !empty($element['#value']['url']))) ? TRUE : FALSE,
  761. '#default_value' => isset($element['#value']['title']) ? $element['#value']['title'] : NULL,
  762. );
  763. }
  764. // Initialize field attributes as an array if it is not an array yet.
  765. if (!is_array($settings['attributes'])) {
  766. $settings['attributes'] = array();
  767. }
  768. // Add default attributes.
  769. $settings['attributes'] += _link_default_attributes();
  770. $attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $settings['attributes'];
  771. if (!empty($settings['attributes']['target']) && $settings['attributes']['target'] == LINK_TARGET_USER) {
  772. $element['attributes']['target'] = array(
  773. '#type' => 'checkbox',
  774. '#title' => t('Open URL in a New Window'),
  775. '#return_value' => LINK_TARGET_NEW_WINDOW,
  776. '#default_value' => isset($attributes['target']) ? $attributes['target'] : FALSE,
  777. );
  778. }
  779. if (!empty($settings['attributes']['configurable_title']) && $settings['attributes']['configurable_title'] == 1) {
  780. $element['attributes']['title'] = array(
  781. '#type' => 'textfield',
  782. '#title' => t('Link "title" attribute'),
  783. '#default_value' => isset($attributes['title']) ? $attributes['title'] : '',
  784. '#field_prefix' => 'title = "',
  785. '#field_suffix' => '"',
  786. );
  787. }
  788. if (!empty($settings['attributes']['configurable_class']) && $settings['attributes']['configurable_class'] == 1) {
  789. $element['attributes']['class'] = array(
  790. '#type' => 'textfield',
  791. '#title' => t('Custom link class'),
  792. '#default_value' => isset($attributes['class']) ? $attributes['class'] : '',
  793. '#field_prefix' => 'class = "',
  794. '#field_suffix' => '"',
  795. );
  796. }
  797. // If the title field is avaliable or there are field accepts multiple values
  798. // then allow the individual field items display the required asterisk if needed.
  799. if (isset($element['title']) || isset($element['_weight'])) {
  800. // To prevent an extra required indicator, disable the required flag on the
  801. // base element since all the sub-fields are already required if desired.
  802. $element['#required'] = FALSE;
  803. }
  804. return $element;
  805. }
  806. /**
  807. * Implements hook_field_formatter_info().
  808. */
  809. function link_field_formatter_info() {
  810. return array(
  811. 'link_default' => array(
  812. 'label' => t('Title, as link (default)'),
  813. 'field types' => array('link_field'),
  814. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  815. ),
  816. 'link_title_plain' => array(
  817. 'label' => t('Title, as plain text'),
  818. 'field types' => array('link_field'),
  819. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  820. ),
  821. 'link_url' => array(
  822. 'label' => t('URL, as link'),
  823. 'field types' => array('link_field'),
  824. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  825. ),
  826. 'link_plain' => array(
  827. 'label' => t('URL, as plain text'),
  828. 'field types' => array('link_field'),
  829. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  830. ),
  831. 'link_absolute' => array(
  832. 'label' => t('URL, absolute'),
  833. 'field types' => array('link_field'),
  834. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  835. ),
  836. 'link_domain' => array(
  837. 'label' => t('Domain, as link'),
  838. 'field types' => array('link_field'),
  839. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  840. 'settings' => array(
  841. 'strip_www' => FALSE,
  842. ),
  843. ),
  844. 'link_short' => array(
  845. 'label' => t('Short, as link with title "Link"'),
  846. 'field types' => array('link_field'),
  847. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  848. ),
  849. 'link_label' => array(
  850. 'label' => t('Label, as link with label as title'),
  851. 'field types' => array('link_field'),
  852. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  853. ),
  854. 'link_separate' => array(
  855. 'label' => t('Separate title and URL'),
  856. 'field types' => array('link_field'),
  857. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  858. ),
  859. );
  860. }
  861. /**
  862. * Implements hook_field_formatter_settings_form().
  863. */
  864. function link_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  865. $display = $instance['display'][$view_mode];
  866. $settings = $display['settings'];
  867. $element = array();
  868. if ($display['type'] == 'link_domain') {
  869. $element['strip_www'] = array(
  870. '#title' => t('Strip www. from domain'),
  871. '#type' => 'checkbox',
  872. '#default_value' => $settings['strip_www'],
  873. );
  874. }
  875. return $element;
  876. }
  877. /**
  878. * Implements hook_field_formatter_settings_summary().
  879. */
  880. function link_field_formatter_settings_summary($field, $instance, $view_mode) {
  881. $display = $instance['display'][$view_mode];
  882. $settings = $display['settings'];
  883. if ($display['type'] == 'link_domain') {
  884. if ($display['settings']['strip_www']) {
  885. return t('Strip www. from domain');
  886. }
  887. else {
  888. return t('Leave www. in domain');
  889. }
  890. }
  891. return '';
  892. }
  893. /**
  894. * Implements hook_field_formatter_view().
  895. */
  896. function link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  897. $elements = array();
  898. foreach ($items as $delta => $item) {
  899. $elements[$delta] = array(
  900. '#theme' => 'link_formatter_' . $display['type'],
  901. '#element' => $item,
  902. '#field' => $instance,
  903. '#display' => $display,
  904. );
  905. }
  906. return $elements;
  907. }
  908. /**
  909. * Formats a link.
  910. */
  911. function theme_link_formatter_link_default($vars) {
  912. $link_options = $vars['element'];
  913. unset($link_options['title']);
  914. unset($link_options['url']);
  915. if (isset($link_options['attributes']['class'])) {
  916. $link_options['attributes']['class'] = array($link_options['attributes']['class']);
  917. }
  918. // Display a normal link if both title and URL are available.
  919. if (!empty($vars['element']['title']) && !empty($vars['element']['url'])) {
  920. return l($vars['element']['title'], $vars['element']['url'], $link_options);
  921. }
  922. // If only a title, display the title.
  923. elseif (!empty($vars['element']['title'])) {
  924. return $link_options['html'] ? $vars['element']['title'] : check_plain($vars['element']['title']);
  925. }
  926. elseif (!empty($vars['element']['url'])) {
  927. return l($vars['element']['title'], $vars['element']['url'], $link_options);
  928. }
  929. }
  930. /**
  931. * Formats a link (or its title) as plain text.
  932. */
  933. function theme_link_formatter_link_plain($vars) {
  934. $link_options = $vars['element'];
  935. if (isset($link_options['title'])) {
  936. unset($link_options['title']);
  937. }
  938. else {
  939. $vars['element']['title'] = '';
  940. }
  941. unset($link_options['url']);
  942. return empty($vars['element']['url']) ? check_plain($vars['element']['title']) : url($vars['element']['url'], $link_options);
  943. }
  944. /**
  945. * Formats a link as an absolute URL.
  946. */
  947. function theme_link_formatter_link_absolute($vars) {
  948. $absolute = array('absolute' => TRUE);
  949. return empty($vars['element']['url']) ? '' : url($vars['element']['url'], $absolute + $vars['element']);
  950. }
  951. /**
  952. * Formats a link using the URL's domain for it's link text.
  953. */
  954. function theme_link_formatter_link_domain($vars) {
  955. $link_options = $vars['element'];
  956. unset($link_options['title']);
  957. unset($link_options['url']);
  958. $domain = parse_url($vars['element']['display_url'], PHP_URL_HOST);
  959. if (!empty($vars['display']['settings']['strip_www'])) {
  960. $domain = str_replace('www.', '', $domain);
  961. }
  962. return $vars['element']['url'] ? l($domain, $vars['element']['url'], $link_options) : '';
  963. }
  964. /**
  965. * Formats a link's title as plain text.
  966. */
  967. function theme_link_formatter_link_title_plain($vars) {
  968. return empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
  969. }
  970. /**
  971. * Formats a link using an alternate display URL for its link text.
  972. */
  973. function theme_link_formatter_link_url($vars) {
  974. $link_options = $vars['element'];
  975. unset($link_options['title']);
  976. unset($link_options['url']);
  977. return $vars['element']['url'] ? l($vars['element']['display_url'], $vars['element']['url'], $link_options) : '';
  978. }
  979. /**
  980. * Formats a link using "Link" as the link text.
  981. */
  982. function theme_link_formatter_link_short($vars) {
  983. $link_options = $vars['element'];
  984. unset($link_options['title']);
  985. unset($link_options['url']);
  986. return $vars['element']['url'] ? l(t('Link'), $vars['element']['url'], $link_options) : '';
  987. }
  988. /**
  989. * Formats a link using the field's label as link text.
  990. */
  991. function theme_link_formatter_link_label($vars) {
  992. $link_options = $vars['element'];
  993. unset($link_options['title']);
  994. unset($link_options['url']);
  995. return $vars['element']['url'] ? l($vars['field']['label'], $vars['element']['url'], $link_options) : '';
  996. }
  997. /**
  998. * Formats a link as separate title and URL elements.
  999. */
  1000. function theme_link_formatter_link_separate($vars) {
  1001. $class = empty($vars['element']['attributes']['class']) ? '' : ' ' . $vars['element']['attributes']['class'];
  1002. unset($vars['element']['attributes']['class']);
  1003. $link_options = $vars['element'];
  1004. unset($link_options['title']);
  1005. unset($link_options['url']);
  1006. $title = empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
  1007. // @TODO static html markup looks not very elegant
  1008. // needs smarter output solution and an optional title/url seperator
  1009. $url_parts = _link_parse_url($vars['element']['url']);
  1010. $output = '';
  1011. $output .= '<div class="link-item ' . $class . '">';
  1012. if (!empty($title)) {
  1013. $output .= '<div class="link-title">' . $title . '</div>';
  1014. }
  1015. $output .= '<div class="link-url">' . l($url_parts['url'], $vars['element']['url'], $link_options) . '</div>';
  1016. $output .= '</div>';
  1017. return $output;
  1018. }
  1019. /**
  1020. * Implements hook_token_list().
  1021. *
  1022. * @TODO: hook_token_list no longer exists - this should change to hook_token_info().
  1023. */
  1024. function link_token_list($type = 'all') {
  1025. if ($type === 'field' || $type === 'all') {
  1026. $tokens = array();
  1027. $tokens['link']['url'] = t("Link URL");
  1028. $tokens['link']['title'] = t("Link title");
  1029. $tokens['link']['view'] = t("Formatted html link");
  1030. return $tokens;
  1031. }
  1032. }
  1033. /**
  1034. * Implements hook_token_values().
  1035. *
  1036. * @TODO: hook_token_values no longer exists - this should change to hook_tokens().
  1037. */
  1038. function link_token_values($type, $object = NULL) {
  1039. if ($type === 'field') {
  1040. $item = $object[0];
  1041. $tokens['url'] = $item['url'];
  1042. $tokens['title'] = $item['title'];
  1043. $tokens['view'] = isset($item['view']) ? $item['view'] : '';
  1044. return $tokens;
  1045. }
  1046. }
  1047. /**
  1048. * Implements hook_views_api().
  1049. */
  1050. function link_views_api() {
  1051. return array(
  1052. 'api' => 2,
  1053. 'path' => drupal_get_path('module', 'link') . '/views',
  1054. );
  1055. }
  1056. /**
  1057. * Forms a valid URL if possible from an entered address.
  1058. *
  1059. * Trims whitespace and automatically adds an http:// to addresses without a
  1060. * protocol specified
  1061. *
  1062. * @param string $url
  1063. * The url entered by the user.
  1064. * @param string $protocol
  1065. * The protocol to be prepended to the url if one is not specified
  1066. */
  1067. function link_cleanup_url($url, $protocol = 'http') {
  1068. $url = trim($url);
  1069. $type = link_validate_url($url);
  1070. if ($type === LINK_EXTERNAL) {
  1071. // Check if there is no protocol specified.
  1072. $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
  1073. if (empty($protocol_match)) {
  1074. // But should there be? Add an automatic http:// if it starts with a domain name.
  1075. $LINK_DOMAINS = _link_domains();
  1076. $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(' . $LINK_DOMAINS . '|[a-z]{2}))/i', $url);
  1077. if (!empty($domain_match)) {
  1078. $url = $protocol . "://" . $url;
  1079. }
  1080. }
  1081. }
  1082. return $url;
  1083. }
  1084. /**
  1085. * Validates a URL.
  1086. *
  1087. * Accepts all URLs following RFC 1738 standard for URL formation and all e-mail
  1088. * addresses following the RFC 2368 standard for mailto address formation.
  1089. *
  1090. * @param string $text
  1091. * Url to be validated.
  1092. *
  1093. * @return mixed
  1094. * Returns boolean FALSE if the URL is not valid. On success, returns one of
  1095. * the LINK_(linktype) constants.
  1096. */
  1097. function link_validate_url($text) {
  1098. // @TODO Complete letters.
  1099. $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array(
  1100. "&#x00E6;", // æ
  1101. "&#x00C6;", // Æ
  1102. "&#x00C0;", // À
  1103. "&#x00E0;", // à
  1104. "&#x00C1;", // Á
  1105. "&#x00E1;", // á
  1106. "&#x00C2;", // Â
  1107. "&#x00E2;", // â
  1108. "&#x00E5;", // å
  1109. "&#x00C5;", // Å
  1110. "&#x00E4;", // ä
  1111. "&#x00C4;", // Ä
  1112. "&#x00C7;", // Ç
  1113. "&#x00E7;", // ç
  1114. "&#x00D0;", // Ð
  1115. "&#x00F0;", // ð
  1116. "&#x00C8;", // È
  1117. "&#x00E8;", // è
  1118. "&#x00C9;", // É
  1119. "&#x00E9;", // é
  1120. "&#x00CA;", // Ê
  1121. "&#x00EA;", // ê
  1122. "&#x00CB;", // Ë
  1123. "&#x00EB;", // ë
  1124. "&#x00CE;", // Î
  1125. "&#x00EE;", // î
  1126. "&#x00CF;", // Ï
  1127. "&#x00EF;", // ï
  1128. "&#x00F8;", // ø
  1129. "&#x00D8;", // Ø
  1130. "&#x00F6;", // ö
  1131. "&#x00D6;", // Ö
  1132. "&#x00D4;", // Ô
  1133. "&#x00F4;", // ô
  1134. "&#x00D5;", // Õ
  1135. "&#x00F5;", // õ
  1136. "&#x0152;", // Œ
  1137. "&#x0153;", // œ
  1138. "&#x00FC;", // ü
  1139. "&#x00DC;", // Ü
  1140. "&#x00D9;", // Ù
  1141. "&#x00F9;", // ù
  1142. "&#x00DB;", // Û
  1143. "&#x00FB;", // û
  1144. "&#x0178;", // Ÿ
  1145. "&#x00FF;", // ÿ
  1146. "&#x00D1;", // Ñ
  1147. "&#x00F1;", // ñ
  1148. "&#x00FE;", // þ
  1149. "&#x00DE;", // Þ
  1150. "&#x00FD;", // ý
  1151. "&#x00DD;", // Ý
  1152. "&#x00BF;", // ¿
  1153. )), ENT_QUOTES, 'UTF-8');
  1154. $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
  1155. "&#x00DF;", // ß
  1156. )), ENT_QUOTES, 'UTF-8');
  1157. $allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
  1158. $LINK_DOMAINS = _link_domains();
  1159. // Starting a parenthesis group with (?: means that it is grouped, but is not captured.
  1160. $protocol = '((?:' . implode("|", $allowed_protocols) . '):\/\/)';
  1161. $authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w" . $LINK_ICHARS . "\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
  1162. $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*(' . $LINK_DOMAINS . '|[a-z]{2}))?)';
  1163. $ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
  1164. $ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
  1165. $port = '(?::([0-9]{1,5}))';
  1166. // Pattern specific to external links.
  1167. $external_pattern = '/^' . $protocol . '?' . $authentication . '?(' . $domain . '|' . $ipv4 . '|' . $ipv6 . ' |localhost)' . $port . '?';
  1168. // Pattern specific to internal links.
  1169. $internal_pattern = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\] ]+)";
  1170. $internal_pattern_file = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)]+)$/i";
  1171. $directories = "(?:\/[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'#!():;*@\[\]]*)*";
  1172. // Yes, four backslashes == a single backslash.
  1173. $query = "(?:\/?\?([?a-z0-9" . $LINK_ICHARS . "+_|\-\.~\/\\\\%=&,$'!():;*@\[\]{} ]*))";
  1174. $anchor = "(?:#[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
  1175. // The rest of the path for a standard URL.
  1176. $end = $directories . '?' . $query . '?' . $anchor . '?' . '$/i';
  1177. $message_id = '[^@].*@' . $domain;
  1178. $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
  1179. $news_pattern = '/^news:(' . $newsgroup_name . '|' . $message_id . ')$/i';
  1180. $user = '[a-zA-Z0-9' . $LINK_ICHARS . '_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
  1181. $email_pattern = '/^mailto:' . $user . '@' . '(?:' . $domain . '|' . $ipv4 . '|' . $ipv6 . '|localhost)' . $query . '?$/';
  1182. if (strpos($text, '<front>') === 0) {
  1183. return LINK_FRONT;
  1184. }
  1185. if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
  1186. return LINK_EMAIL;
  1187. }
  1188. if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
  1189. return LINK_NEWS;
  1190. }
  1191. if (preg_match($internal_pattern . $end, $text)) {
  1192. return LINK_INTERNAL;
  1193. }
  1194. if (preg_match($external_pattern . $end, $text)) {
  1195. return LINK_EXTERNAL;
  1196. }
  1197. if (preg_match($internal_pattern_file, $text)) {
  1198. return LINK_INTERNAL;
  1199. }
  1200. return FALSE;
  1201. }
  1202. /**
  1203. * Returns the list of allowed domains, including domains added by admins via variable_set/$config.
  1204. */
  1205. function _link_domains() {
  1206. $link_extra_domains = variable_get('link_extra_domains', array());
  1207. return empty($link_extra_domains) ? LINK_DOMAINS : LINK_DOMAINS . '|' . implode('|', $link_extra_domains);
  1208. }
  1209. /**
  1210. * Implements hook_migrate_field_alter().
  1211. */
  1212. function link_content_migrate_field_alter(&$field_value, $instance_value) {
  1213. if ($field_value['type'] == 'link') {
  1214. // Adjust the field type.
  1215. $field_value['type'] = 'link_field';
  1216. // Remove settings that are now on the instance.
  1217. foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
  1218. unset($field_value['settings'][$setting]);
  1219. }
  1220. }
  1221. }
  1222. /**
  1223. * Implements hook_migrate_instance_alter().
  1224. *
  1225. * Widget type also changed to link_field.
  1226. */
  1227. function link_content_migrate_instance_alter(&$instance_value, $field_value) {
  1228. if ($field_value['type'] == 'link') {
  1229. // Grab settings that were previously on the field.
  1230. foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
  1231. if (isset($field_value['settings'][$setting])) {
  1232. $instance_value['settings'][$setting] = $field_value['settings'][$setting];
  1233. }
  1234. }
  1235. // Adjust widget type.
  1236. if ($instance_value['widget']['type'] == 'link') {
  1237. $instance_value['widget']['type'] = 'link_field';
  1238. }
  1239. // Adjust formatter types.
  1240. foreach ($instance_value['display'] as $context => $settings) {
  1241. if (in_array($settings['type'], array('default', 'title_plain', 'url', 'plain', 'short', 'label', 'separate'))) {
  1242. $instance_value['display'][$context]['type'] = 'link_' . $settings['type'];
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Implements hook_field_settings_form().
  1249. */
  1250. function link_field_settings_form() {
  1251. return array();
  1252. }
  1253. /**
  1254. * Additional callback to adapt the property info of link fields.
  1255. *
  1256. * @see entity_metadata_field_entity_property_info()
  1257. */
  1258. function link_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  1259. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  1260. // Define a data structure so it's possible to deal with both the link title
  1261. // and URL.
  1262. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  1263. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  1264. // Auto-create the field item as soon as a property is set.
  1265. $property['auto creation'] = 'link_field_item_create';
  1266. $property['property info'] = link_field_item_property_info();
  1267. $property['property info']['url']['required'] = !$instance['settings']['url'];
  1268. $property['property info']['title']['required'] = ($instance['settings']['title'] == 'required');
  1269. if ($instance['settings']['title'] == 'none') {
  1270. unset($property['property info']['title']);
  1271. }
  1272. unset($property['query callback']);
  1273. }
  1274. /**
  1275. * Callback for creating a new, empty link field item.
  1276. *
  1277. * @see link_field_property_info_callback()
  1278. */
  1279. function link_field_item_create() {
  1280. return array('title' => NULL, 'url' => NULL);
  1281. }
  1282. /**
  1283. * Defines info for the properties of the link-field item data structure.
  1284. */
  1285. function link_field_item_property_info() {
  1286. $properties['title'] = array(
  1287. 'type' => 'text',
  1288. 'label' => t('The title of the link.'),
  1289. 'setter callback' => 'entity_property_verbatim_set',
  1290. );
  1291. $properties['url'] = array(
  1292. 'type' => 'uri',
  1293. 'label' => t('The URL of the link.'),
  1294. 'setter callback' => 'entity_property_verbatim_set',
  1295. );
  1296. $properties['attributes'] = array(
  1297. 'type' => 'struct',
  1298. 'label' => t('The attributes of the link.'),
  1299. 'setter callback' => 'entity_property_verbatim_set',
  1300. 'getter callback' => 'link_attribute_property_get',
  1301. );
  1302. return $properties;
  1303. }
  1304. /**
  1305. * Entity property info getter callback for link attributes.
  1306. */
  1307. function link_attribute_property_get($data, array $options, $name, $type, $info) {
  1308. return isset($data[$name]) ? array_filter($data[$name]) : array();
  1309. }
  1310. /**
  1311. * Implements hook_field_update_instance().
  1312. */
  1313. function link_field_update_instance($instance, $prior_instance) {
  1314. if (function_exists('i18n_string_update') && $instance['widget']['type'] == 'link_field' && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {
  1315. $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
  1316. i18n_string_update($i18n_string_name, $instance['settings']['title_value']);
  1317. }
  1318. }
  1319. /**
  1320. * Implements hook_i18n_string_list_TEXTGROUP_alter().
  1321. */
  1322. function link_i18n_string_list_field_alter(&$strings, $type = NULL, $object = NULL) {
  1323. if ($type != 'field_instance' || !is_array($object) || !isset($object['widget']['type'])) {
  1324. return;
  1325. }
  1326. if ($object['widget']['type'] == 'link_field' && isset($object['settings']['title_value'])) {
  1327. $strings['field'][$object['field_name']][$object['bundle']]['title_value']['string'] = $object['settings']['title_value'];
  1328. }
  1329. }