link.module 47 KB

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