link.module 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  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. Only alphanumeric characters and hyphens are allowed'),
  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, $instance);
  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, $instance);
  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. * @param $item
  345. * Link field values.
  346. *
  347. * @param $delta
  348. * The sequence number for current values.
  349. *
  350. * @param $field
  351. * The field structure array.
  352. *
  353. * @param $entity
  354. * Entity object.
  355. *
  356. * @param $instance
  357. * The instance structure for $field on $entity's bundle.
  358. *
  359. */
  360. function _link_process(&$item, $delta, $field, $entity, $instance) {
  361. // Trim whitespace from URL.
  362. if (!empty($item['url'])) {
  363. $item['url'] = trim($item['url']);
  364. }
  365. // If no attributes are set then make sure $item['attributes'] is an empty
  366. // array, so $field['attributes'] can override it.
  367. if (empty($item['attributes'])) {
  368. $item['attributes'] = array();
  369. }
  370. // Serialize the attributes array.
  371. if (!is_string($item['attributes'])) {
  372. $item['attributes'] = serialize($item['attributes']);
  373. }
  374. // Don't save an invalid default value (e.g. 'http://').
  375. if ((isset($field['widget']['default_value'][$delta]['url']) && $item['url'] == $field['widget']['default_value'][$delta]['url']) && is_object($entity)) {
  376. $langcode = !empty($entity) ? field_language($instance['entity_type'], $entity, $instance['field_name']) : LANGUAGE_NONE;
  377. if (!link_validate_url($item['url'], $langcode)) {
  378. unset($item['url']);
  379. }
  380. }
  381. }
  382. /**
  383. * Validates that the link field has been entered properly.
  384. */
  385. function _link_validate(&$item, $delta, $field, $entity, $instance, $langcode, &$optional_field_found, &$errors) {
  386. if ($item['url'] && !(isset($instance['default_value'][$delta]['url']) && $item['url'] === $instance['default_value'][$delta]['url'] && !$instance['required'])) {
  387. // Validate the link.
  388. if (!link_validate_url(trim($item['url']), $langcode)) {
  389. $errors[$field['field_name']][$langcode][$delta][] = array(
  390. 'error' => 'link_required',
  391. 'message' => t('The value %value provided for %field is not a valid URL.', array(
  392. '%value' => trim($item['url']),
  393. '%field' => $instance['label'],
  394. )),
  395. 'error_element' => array('url' => TRUE, 'title' => FALSE),
  396. );
  397. }
  398. // Require a title for the link if necessary.
  399. if ($instance['settings']['title'] == 'required' && strlen(trim($item['title'])) == 0) {
  400. $errors[$field['field_name']][$langcode][$delta][] = array(
  401. 'error' => 'link_required',
  402. 'message' => t('Titles are required for all links.'),
  403. 'error_element' => array('url' => FALSE, 'title' => TRUE),
  404. );
  405. }
  406. }
  407. // Require a link if we have a title.
  408. if ($instance['settings']['url'] !== 'optional' && strlen(isset($item['title']) ? $item['title'] : NULL) > 0 && strlen(trim($item['url'])) == 0) {
  409. $errors[$field['field_name']][$langcode][$delta][] = array(
  410. 'error' => 'link_required',
  411. 'message' => t('You cannot enter a title without a link url.'),
  412. 'error_element' => array('url' => TRUE, 'title' => FALSE),
  413. );
  414. }
  415. // In a totally bizzaro case, where URLs and titles are optional but the field is required, ensure there is at least one link.
  416. if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional'
  417. && (strlen(trim($item['url'])) !== 0 || strlen(trim($item['title'])) !== 0)) {
  418. $optional_field_found = TRUE;
  419. }
  420. // Require entire field.
  421. if ($instance['settings']['url'] === 'optional' && $instance['settings']['title'] === 'optional' && $instance['required'] == 1 && !$optional_field_found && isset($instance['id'])) {
  422. $errors[$field['field_name']][$langcode][$delta][] = array(
  423. 'error' => 'link_required',
  424. 'message' => t('At least one title or URL must be entered.'),
  425. 'error_element' => array('url' => FALSE, 'title' => TRUE),
  426. );
  427. }
  428. }
  429. /**
  430. * Clean up user-entered values for a link field according to field settings.
  431. *
  432. * @param array $item
  433. * A single link item, usually containing url, title, and attributes.
  434. * @param int $delta
  435. * The delta value if this field is one of multiple fields.
  436. * @param array $field
  437. * The CCK field definition.
  438. * @param object $entity
  439. * The entity containing this link.
  440. */
  441. function _link_sanitize(&$item, $delta, &$field, $instance, &$entity) {
  442. // Don't try to process empty links.
  443. if (empty($item['url']) && empty($item['title'])) {
  444. return;
  445. }
  446. if (empty($item['html'])) {
  447. $item['html'] = FALSE;
  448. }
  449. // Replace URL tokens.
  450. $entity_type = $instance['entity_type'];
  451. $entity_info = entity_get_info($entity_type);
  452. $property_id = $entity_info['entity keys']['id'];
  453. $entity_token_type = isset($entity_info['token type']) ? $entity_info['token type'] : (
  454. $entity_type == 'taxonomy_term' || $entity_type == 'taxonomy_vocabulary' ? str_replace('taxonomy_', '', $entity_type) : $entity_type
  455. );
  456. if (isset($instance['settings']['enable_tokens']) && $instance['settings']['enable_tokens']) {
  457. $text_tokens = token_scan($item['url']);
  458. if (!empty($text_tokens)) {
  459. // Load the entity if necessary for entities in views.
  460. if (isset($entity->{$property_id})) {
  461. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  462. $entity_loaded = array_pop($entity_loaded);
  463. }
  464. else {
  465. $entity_loaded = $entity;
  466. }
  467. $item['url'] = token_replace($item['url'], array($entity_token_type => $entity_loaded));
  468. }
  469. }
  470. $type = link_url_type($item['url']);
  471. // If the type of the URL cannot be determined and URL validation is disabled,
  472. // then assume LINK_EXTERNAL for later processing.
  473. if ($type == FALSE && $instance['settings']['validate_url'] === 0) {
  474. $type = LINK_EXTERNAL;
  475. }
  476. $url = link_cleanup_url($item['url']);
  477. $url_parts = _link_parse_url($url);
  478. if (!empty($url_parts['url'])) {
  479. $item['url'] = url($url_parts['url'],
  480. array('query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
  481. 'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
  482. 'absolute' => !empty($instance['settings']['absolute_url']),
  483. 'html' => TRUE,
  484. )
  485. );
  486. }
  487. // Create a shortened URL for display.
  488. if ($type == LINK_EMAIL) {
  489. $display_url = str_replace('mailto:', '', $url);
  490. }
  491. else {
  492. $display_url = url($url_parts['url'],
  493. array(
  494. 'query' => isset($url_parts['query']) ? $url_parts['query'] : NULL,
  495. 'fragment' => isset($url_parts['fragment']) ? $url_parts['fragment'] : NULL,
  496. 'absolute' => !empty($instance['settings']['absolute_url']),
  497. )
  498. );
  499. }
  500. if ($instance['settings']['display']['url_cutoff'] && strlen($display_url) > $instance['settings']['display']['url_cutoff']) {
  501. $display_url = substr($display_url, 0, $instance['settings']['display']['url_cutoff']) . "...";
  502. }
  503. $item['display_url'] = $display_url;
  504. // Use the title defined at the instance level.
  505. if ($instance['settings']['title'] == 'value' && strlen(trim($instance['settings']['title_value']))) {
  506. $title = $instance['settings']['title_value'];
  507. if (function_exists('i18n_string_translate')) {
  508. $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
  509. $title = i18n_string_translate($i18n_string_name, $title);
  510. }
  511. }
  512. // Use the title defined by the user at the widget level.
  513. elseif (isset($item['title'])) {
  514. $title = $item['title'];
  515. }
  516. else {
  517. $title = '';
  518. }
  519. // Replace title tokens.
  520. if ($title && ($instance['settings']['title'] == 'value' || $instance['settings']['enable_tokens'])) {
  521. $text_tokens = token_scan($title);
  522. if (!empty($text_tokens)) {
  523. // Load the entity if necessary for entities in views.
  524. if (isset($entity->{$property_id})) {
  525. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  526. $entity_loaded = array_pop($entity_loaded);
  527. }
  528. else {
  529. $entity_loaded = $entity;
  530. }
  531. $title = token_replace($title, array($entity_token_type => $entity_loaded));
  532. }
  533. $title = filter_xss($title, array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
  534. $item['html'] = TRUE;
  535. }
  536. $item['title'] = empty($title) ? $item['display_url'] : $title;
  537. if (!isset($item['attributes'])) {
  538. $item['attributes'] = array();
  539. }
  540. // Unserialize attributtes array if it has not been unserialized yet.
  541. if (!is_array($item['attributes'])) {
  542. $item['attributes'] = (array) unserialize($item['attributes']);
  543. }
  544. // Add default attributes.
  545. if (!is_array($instance['settings']['attributes'])) {
  546. $instance['settings']['attributes'] = _link_default_attributes();
  547. }
  548. else {
  549. $instance['settings']['attributes'] += _link_default_attributes();
  550. }
  551. // Merge item attributes with attributes defined at the field level.
  552. $item['attributes'] += $instance['settings']['attributes'];
  553. // If user is not allowed to choose target attribute, use default defined at
  554. // field level.
  555. if ($instance['settings']['attributes']['target'] != LINK_TARGET_USER) {
  556. $item['attributes']['target'] = $instance['settings']['attributes']['target'];
  557. }
  558. elseif ($item['attributes']['target'] == LINK_TARGET_USER) {
  559. $item['attributes']['target'] = LINK_TARGET_DEFAULT;
  560. }
  561. // Remove the target attribute if the default (no target) is selected.
  562. if (empty($item['attributes']) || (isset($item['attributes']['target']) && $item['attributes']['target'] == LINK_TARGET_DEFAULT)) {
  563. unset($item['attributes']['target']);
  564. }
  565. // Remove rel attribute for internal or external links if selected.
  566. if (isset($item['attributes']['rel']) && isset($instance['settings']['rel_remove']) && $instance['settings']['rel_remove'] != 'default') {
  567. if (($instance['settings']['rel_remove'] != 'rel_remove_internal' && $type != LINK_INTERNAL) ||
  568. ($instance['settings']['rel_remove'] != 'rel_remove_external' && $type != LINK_EXTERNAL)) {
  569. unset($item['attributes']['rel']);
  570. }
  571. }
  572. // Handle "title" link attribute.
  573. if (!empty($item['attributes']['title']) && module_exists('token')) {
  574. $text_tokens = token_scan($item['attributes']['title']);
  575. if (!empty($text_tokens)) {
  576. // Load the entity (necessary for entities in views).
  577. if (isset($entity->{$property_id})) {
  578. $entity_loaded = entity_load($entity_type, array($entity->{$property_id}));
  579. $entity_loaded = array_pop($entity_loaded);
  580. }
  581. else {
  582. $entity_loaded = $entity;
  583. }
  584. $item['attributes']['title'] = token_replace($item['attributes']['title'], array($entity_token_type => $entity_loaded));
  585. }
  586. $item['attributes']['title'] = filter_xss($item['attributes']['title'], array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
  587. }
  588. // Handle attribute classes.
  589. if (!empty($item['attributes']['class'])) {
  590. $classes = explode(' ', $item['attributes']['class']);
  591. foreach ($classes as &$class) {
  592. $class = drupal_clean_css_identifier($class);
  593. }
  594. $item['attributes']['class'] = implode(' ', $classes);
  595. }
  596. unset($item['attributes']['configurable_class']);
  597. // Remove title attribute if it's equal to link text.
  598. if (isset($item['attributes']['title']) && $item['attributes']['title'] == $item['title']) {
  599. unset($item['attributes']['title']);
  600. }
  601. unset($item['attributes']['configurable_title']);
  602. // Remove empty attributes.
  603. $item['attributes'] = array_filter($item['attributes']);
  604. }
  605. /**
  606. * Because parse_url doesn't work with relative urls.
  607. *
  608. * @param string $url
  609. * URL to parse.
  610. *
  611. * @return array
  612. * Array of url pieces - only 'url', 'query', and 'fragment'.
  613. */
  614. function _link_parse_url($url) {
  615. $url_parts = array();
  616. // Separate out the anchor, if any.
  617. if (strpos($url, '#') !== FALSE) {
  618. $url_parts['fragment'] = substr($url, strpos($url, '#') + 1);
  619. $url = substr($url, 0, strpos($url, '#'));
  620. }
  621. // Separate out the query string, if any.
  622. if (strpos($url, '?') !== FALSE) {
  623. $query = substr($url, strpos($url, '?') + 1);
  624. $url_parts['query'] = _link_parse_str($query);
  625. $url = substr($url, 0, strpos($url, '?'));
  626. }
  627. $url_parts['url'] = $url;
  628. return $url_parts;
  629. }
  630. /**
  631. * Replaces the PHP parse_str() function.
  632. *
  633. * Because parse_str replaces the following characters in query parameters name
  634. * in order to maintain compatibility with deprecated register_globals directive:
  635. *
  636. * - chr(32) ( ) (space)
  637. * - chr(46) (.) (dot)
  638. * - chr(91) ([) (open square bracket)
  639. * - chr(128) - chr(159) (various)
  640. *
  641. * @param string $query
  642. * Query to parse.
  643. *
  644. * @return array
  645. * Array of query parameters.
  646. *
  647. * @see http://php.net/manual/en/language.variables.external.php#81080
  648. */
  649. function _link_parse_str($query) {
  650. $query_array = array();
  651. $pairs = explode('&', $query);
  652. foreach ($pairs as $pair) {
  653. $name_value = explode('=', $pair, 2);
  654. $name = urldecode($name_value[0]);
  655. $value = isset($name_value[1]) ? urldecode($name_value[1]) : NULL;
  656. $query_array[$name] = $value;
  657. }
  658. return $query_array;
  659. }
  660. /**
  661. * Implements hook_theme().
  662. */
  663. function link_theme() {
  664. return array(
  665. 'link_formatter_link_default' => array(
  666. 'variables' => array('element' => NULL, 'field' => NULL),
  667. ),
  668. 'link_formatter_link_plain' => array(
  669. 'variables' => array('element' => NULL, 'field' => NULL),
  670. ),
  671. 'link_formatter_link_host' => array(
  672. 'variables' => array('element' => NULL),
  673. ),
  674. 'link_formatter_link_absolute' => array(
  675. 'variables' => array('element' => NULL, 'field' => NULL),
  676. ),
  677. 'link_formatter_link_domain' => array(
  678. 'variables' => array('element' => NULL, 'display' => NULL, 'field' => NULL),
  679. ),
  680. 'link_formatter_link_title_plain' => array(
  681. 'variables' => array('element' => NULL, 'field' => NULL),
  682. ),
  683. 'link_formatter_link_url' => array(
  684. 'variables' => array('element' => NULL, 'field' => NULL),
  685. ),
  686. 'link_formatter_link_short' => array(
  687. 'variables' => array('element' => NULL, 'field' => NULL),
  688. ),
  689. 'link_formatter_link_label' => array(
  690. 'variables' => array('element' => NULL, 'field' => NULL),
  691. ),
  692. 'link_formatter_link_separate' => array(
  693. 'variables' => array('element' => NULL, 'field' => NULL),
  694. ),
  695. 'link_field' => array(
  696. 'render element' => 'element',
  697. ),
  698. );
  699. }
  700. /**
  701. * Formats a link field widget.
  702. */
  703. function theme_link_field($vars) {
  704. drupal_add_css(drupal_get_path('module', 'link') . '/link.css');
  705. $element = $vars['element'];
  706. // Prefix single value link fields with the name of the field.
  707. if (empty($element['#field']['multiple'])) {
  708. if (isset($element['url']) && !isset($element['title'])) {
  709. $element['url']['#title_display'] = 'invisible';
  710. }
  711. }
  712. $output = '';
  713. $output .= '<div class="link-field-subrow clearfix">';
  714. if (isset($element['title'])) {
  715. $output .= '<div class="link-field-title link-field-column">' . drupal_render($element['title']) . '</div>';
  716. }
  717. $output .= '<div class="link-field-url' . (isset($element['title']) ? ' link-field-column' : '') . '">' . drupal_render($element['url']) . '</div>';
  718. $output .= '</div>';
  719. if (!empty($element['attributes']['target'])) {
  720. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['target']) . '</div>';
  721. }
  722. if (!empty($element['attributes']['title'])) {
  723. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['title']) . '</div>';
  724. }
  725. if (!empty($element['attributes']['class'])) {
  726. $output .= '<div class="link-attributes">' . drupal_render($element['attributes']['class']) . '</div>';
  727. }
  728. $output .= drupal_render_children($element);
  729. return $output;
  730. }
  731. /**
  732. * Implements hook_element_info().
  733. */
  734. function link_element_info() {
  735. $elements = array();
  736. $elements['link_field'] = array(
  737. '#input' => TRUE,
  738. '#process' => array('link_field_process'),
  739. '#theme' => 'link_field',
  740. '#theme_wrappers' => array('form_element'),
  741. );
  742. return $elements;
  743. }
  744. /**
  745. * Returns the default attributes and their values.
  746. */
  747. function _link_default_attributes() {
  748. return array(
  749. 'target' => LINK_TARGET_DEFAULT,
  750. 'class' => '',
  751. 'rel' => '',
  752. );
  753. }
  754. /**
  755. * Processes the link type element before displaying the field.
  756. *
  757. * Build the form element. When creating a form using FAPI #process,
  758. * note that $element['#value'] is already set.
  759. *
  760. * The $fields array is in $complete_form['#field_info'][$element['#field_name']].
  761. */
  762. function link_field_process($element, $form_state, $complete_form) {
  763. $instance = field_widget_instance($element, $form_state);
  764. $settings = $instance['settings'];
  765. $element['url'] = array(
  766. '#type' => 'textfield',
  767. '#maxlength' => LINK_URL_MAX_LENGTH,
  768. '#title' => t('URL'),
  769. '#required' => ($element['#delta'] == 0 && $settings['url'] !== 'optional') ? $element['#required'] : FALSE,
  770. '#default_value' => isset($element['#value']['url']) ? $element['#value']['url'] : NULL,
  771. );
  772. if ($settings['title'] !== 'none' && $settings['title'] !== 'value') {
  773. // Figure out the label of the title field.
  774. if (!empty($settings['title_label_use_field_label'])) {
  775. // Use the element label as the title field label.
  776. $title_label = $element['#title'];
  777. // Hide the field label because there is no need for the duplicate labels.
  778. $element['#title_display'] = 'invisible';
  779. }
  780. else {
  781. $title_label = t('Title');
  782. }
  783. $element['title'] = array(
  784. '#type' => 'textfield',
  785. '#maxlength' => $settings['title_maxlength'],
  786. '#title' => $title_label,
  787. '#description' => t('The link title is limited to @maxlength characters maximum.', array('@maxlength' => $settings['title_maxlength'])),
  788. '#required' => ($settings['title'] == 'required' && (($element['#delta'] == 0 && $element['#required']) || !empty($element['#value']['url']))) ? TRUE : FALSE,
  789. '#default_value' => isset($element['#value']['title']) ? $element['#value']['title'] : NULL,
  790. );
  791. }
  792. // Initialize field attributes as an array if it is not an array yet.
  793. if (!is_array($settings['attributes'])) {
  794. $settings['attributes'] = array();
  795. }
  796. // Add default attributes.
  797. $settings['attributes'] += _link_default_attributes();
  798. $attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $settings['attributes'];
  799. if (!empty($settings['attributes']['target']) && $settings['attributes']['target'] == LINK_TARGET_USER) {
  800. $element['attributes']['target'] = array(
  801. '#type' => 'checkbox',
  802. '#title' => t('Open URL in a New Window'),
  803. '#return_value' => LINK_TARGET_NEW_WINDOW,
  804. '#default_value' => isset($attributes['target']) ? $attributes['target'] : FALSE,
  805. );
  806. }
  807. if (!empty($settings['attributes']['configurable_title']) && $settings['attributes']['configurable_title'] == 1) {
  808. $element['attributes']['title'] = array(
  809. '#type' => 'textfield',
  810. '#title' => t('Link "title" attribute'),
  811. '#default_value' => isset($attributes['title']) ? $attributes['title'] : '',
  812. '#field_prefix' => 'title = "',
  813. '#field_suffix' => '"',
  814. );
  815. }
  816. if (!empty($settings['attributes']['configurable_class']) && $settings['attributes']['configurable_class'] == 1) {
  817. $element['attributes']['class'] = array(
  818. '#type' => 'textfield',
  819. '#title' => t('Custom link class'),
  820. '#default_value' => isset($attributes['class']) ? $attributes['class'] : '',
  821. '#field_prefix' => 'class = "',
  822. '#field_suffix' => '"',
  823. );
  824. }
  825. // If the title field is available or there are field accepts multiple values
  826. // then allow the individual field items display the required asterisk if needed.
  827. if (isset($element['title']) || isset($element['_weight'])) {
  828. // To prevent an extra required indicator, disable the required flag on the
  829. // base element since all the sub-fields are already required if desired.
  830. $element['#required'] = FALSE;
  831. }
  832. return $element;
  833. }
  834. /**
  835. * Implements hook_field_formatter_info().
  836. */
  837. function link_field_formatter_info() {
  838. return array(
  839. 'link_default' => array(
  840. 'label' => t('Title, as link (default)'),
  841. 'field types' => array('link_field'),
  842. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  843. ),
  844. 'link_title_plain' => array(
  845. 'label' => t('Title, as plain text'),
  846. 'field types' => array('link_field'),
  847. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  848. ),
  849. 'link_host' => array(
  850. 'label' => t('Host, as plain text'),
  851. 'field types' => array('link_field'),
  852. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  853. ),
  854. 'link_url' => array(
  855. 'label' => t('URL, as link'),
  856. 'field types' => array('link_field'),
  857. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  858. ),
  859. 'link_plain' => array(
  860. 'label' => t('URL, as plain text'),
  861. 'field types' => array('link_field'),
  862. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  863. ),
  864. 'link_absolute' => array(
  865. 'label' => t('URL, absolute'),
  866. 'field types' => array('link_field'),
  867. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  868. ),
  869. 'link_domain' => array(
  870. 'label' => t('Domain, as link'),
  871. 'field types' => array('link_field'),
  872. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  873. 'settings' => array(
  874. 'strip_www' => FALSE,
  875. ),
  876. ),
  877. 'link_short' => array(
  878. 'label' => t('Short, as link with title "Link"'),
  879. 'field types' => array('link_field'),
  880. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  881. ),
  882. 'link_label' => array(
  883. 'label' => t('Label, as link with label as title'),
  884. 'field types' => array('link_field'),
  885. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  886. ),
  887. 'link_separate' => array(
  888. 'label' => t('Separate title and URL'),
  889. 'field types' => array('link_field'),
  890. 'multiple values' => FIELD_BEHAVIOR_DEFAULT,
  891. ),
  892. );
  893. }
  894. /**
  895. * Implements hook_field_formatter_settings_form().
  896. */
  897. function link_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  898. $display = $instance['display'][$view_mode];
  899. $settings = $display['settings'];
  900. $element = array();
  901. if ($display['type'] == 'link_domain') {
  902. $element['strip_www'] = array(
  903. '#title' => t('Strip www. from domain'),
  904. '#type' => 'checkbox',
  905. '#default_value' => $settings['strip_www'],
  906. );
  907. }
  908. return $element;
  909. }
  910. /**
  911. * Implements hook_field_formatter_settings_summary().
  912. */
  913. function link_field_formatter_settings_summary($field, $instance, $view_mode) {
  914. $display = $instance['display'][$view_mode];
  915. $settings = $display['settings'];
  916. if ($display['type'] == 'link_domain') {
  917. if ($display['settings']['strip_www']) {
  918. return t('Strip www. from domain');
  919. }
  920. else {
  921. return t('Leave www. in domain');
  922. }
  923. }
  924. return '';
  925. }
  926. /**
  927. * Implements hook_field_formatter_view().
  928. */
  929. function link_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  930. $elements = array();
  931. foreach ($items as $delta => $item) {
  932. $elements[$delta] = array(
  933. '#theme' => 'link_formatter_' . $display['type'],
  934. '#element' => $item,
  935. '#field' => $instance,
  936. '#display' => $display,
  937. );
  938. }
  939. return $elements;
  940. }
  941. /**
  942. * Formats a link.
  943. */
  944. function theme_link_formatter_link_default($vars) {
  945. $link_options = $vars['element'];
  946. unset($link_options['title']);
  947. unset($link_options['url']);
  948. if (isset($link_options['attributes']['class'])) {
  949. $link_options['attributes']['class'] = array($link_options['attributes']['class']);
  950. }
  951. // Display a normal link if both title and URL are available.
  952. if (!empty($vars['element']['title']) && !empty($vars['element']['url'])) {
  953. return l($vars['element']['title'], $vars['element']['url'], $link_options);
  954. }
  955. // If only a title, display the title.
  956. elseif (!empty($vars['element']['title'])) {
  957. return $link_options['html'] ? $vars['element']['title'] : check_plain($vars['element']['title']);
  958. }
  959. elseif (!empty($vars['element']['url'])) {
  960. return l($vars['element']['title'], $vars['element']['url'], $link_options);
  961. }
  962. }
  963. /**
  964. * Formats a link (or its title) as plain text.
  965. */
  966. function theme_link_formatter_link_plain($vars) {
  967. $link_options = $vars['element'];
  968. if (isset($link_options['title'])) {
  969. unset($link_options['title']);
  970. }
  971. else {
  972. $vars['element']['title'] = '';
  973. }
  974. unset($link_options['url']);
  975. return empty($vars['element']['url']) ? check_plain($vars['element']['title']) : url($vars['element']['url'], $link_options);
  976. }
  977. /**
  978. * Theme function for 'host' text field formatter.
  979. */
  980. function theme_link_formatter_link_host($vars) {
  981. $host = @parse_url($vars['element']['url']);
  982. return isset($host['host']) ? check_plain($host['host']) : '';
  983. }
  984. /**
  985. * Formats a link as an absolute URL.
  986. */
  987. function theme_link_formatter_link_absolute($vars) {
  988. $absolute = array('absolute' => TRUE);
  989. return empty($vars['element']['url']) ? '' : url($vars['element']['url'], $absolute + $vars['element']);
  990. }
  991. /**
  992. * Formats a link using the URL's domain for it's link text.
  993. */
  994. function theme_link_formatter_link_domain($vars) {
  995. $link_options = $vars['element'];
  996. unset($link_options['title']);
  997. unset($link_options['url']);
  998. $domain = parse_url($vars['element']['display_url'], PHP_URL_HOST);
  999. if (!empty($vars['display']['settings']['strip_www'])) {
  1000. $domain = str_replace('www.', '', $domain);
  1001. }
  1002. return $vars['element']['url'] ? l($domain, $vars['element']['url'], $link_options) : '';
  1003. }
  1004. /**
  1005. * Formats a link's title as plain text.
  1006. */
  1007. function theme_link_formatter_link_title_plain($vars) {
  1008. return empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
  1009. }
  1010. /**
  1011. * Formats a link using an alternate display URL for its link text.
  1012. */
  1013. function theme_link_formatter_link_url($vars) {
  1014. $link_options = $vars['element'];
  1015. unset($link_options['title']);
  1016. unset($link_options['url']);
  1017. return $vars['element']['url'] ? l($vars['element']['display_url'], $vars['element']['url'], $link_options) : '';
  1018. }
  1019. /**
  1020. * Formats a link using "Link" as the link text.
  1021. */
  1022. function theme_link_formatter_link_short($vars) {
  1023. $link_options = $vars['element'];
  1024. unset($link_options['title']);
  1025. unset($link_options['url']);
  1026. return $vars['element']['url'] ? l(t('Link'), $vars['element']['url'], $link_options) : '';
  1027. }
  1028. /**
  1029. * Formats a link using the field's label as link text.
  1030. */
  1031. function theme_link_formatter_link_label($vars) {
  1032. $link_options = $vars['element'];
  1033. unset($link_options['title']);
  1034. unset($link_options['url']);
  1035. return $vars['element']['url'] ? l($vars['field']['label'], $vars['element']['url'], $link_options) : '';
  1036. }
  1037. /**
  1038. * Formats a link as separate title and URL elements.
  1039. */
  1040. function theme_link_formatter_link_separate($vars) {
  1041. $class = empty($vars['element']['attributes']['class']) ? '' : ' ' . $vars['element']['attributes']['class'];
  1042. unset($vars['element']['attributes']['class']);
  1043. $link_options = $vars['element'];
  1044. unset($link_options['title']);
  1045. unset($link_options['url']);
  1046. $title = empty($vars['element']['title']) ? '' : check_plain($vars['element']['title']);
  1047. // @TODO static html markup looks not very elegant
  1048. // needs smarter output solution and an optional title/url seperator
  1049. $url_parts = _link_parse_url($vars['element']['url']);
  1050. $output = '';
  1051. $output .= '<div class="link-item ' . $class . '">';
  1052. if (!empty($title)) {
  1053. $output .= '<div class="link-title">' . $title . '</div>';
  1054. }
  1055. $output .= '<div class="link-url">' . l($url_parts['url'], $vars['element']['url'], $link_options) . '</div>';
  1056. $output .= '</div>';
  1057. return $output;
  1058. }
  1059. /**
  1060. * Implements hook_token_list().
  1061. *
  1062. * @TODO: hook_token_list no longer exists - this should change to hook_token_info().
  1063. */
  1064. function link_token_list($type = 'all') {
  1065. if ($type === 'field' || $type === 'all') {
  1066. $tokens = array();
  1067. $tokens['link']['url'] = t("Link URL");
  1068. $tokens['link']['title'] = t("Link title");
  1069. $tokens['link']['view'] = t("Formatted html link");
  1070. return $tokens;
  1071. }
  1072. }
  1073. /**
  1074. * Implements hook_token_values().
  1075. *
  1076. * @TODO: hook_token_values no longer exists - this should change to hook_tokens().
  1077. */
  1078. function link_token_values($type, $object = NULL) {
  1079. if ($type === 'field') {
  1080. $item = $object[0];
  1081. $tokens['url'] = $item['url'];
  1082. $tokens['title'] = $item['title'];
  1083. $tokens['view'] = isset($item['view']) ? $item['view'] : '';
  1084. return $tokens;
  1085. }
  1086. }
  1087. /**
  1088. * Implements hook_views_api().
  1089. */
  1090. function link_views_api() {
  1091. return array(
  1092. 'api' => 2,
  1093. 'path' => drupal_get_path('module', 'link') . '/views',
  1094. );
  1095. }
  1096. /**
  1097. * Forms a valid URL if possible from an entered address.
  1098. *
  1099. * Trims whitespace and automatically adds an http:// to addresses without a
  1100. * protocol specified
  1101. *
  1102. * @param string $url
  1103. * The url entered by the user.
  1104. * @param string $protocol
  1105. * The protocol to be prepended to the url if one is not specified
  1106. */
  1107. function link_cleanup_url($url, $protocol = 'http') {
  1108. $url = trim($url);
  1109. $type = link_url_type($url);
  1110. if ($type === LINK_EXTERNAL) {
  1111. // Check if there is no protocol specified.
  1112. $protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
  1113. if (empty($protocol_match)) {
  1114. // But should there be? Add an automatic http:// if it starts with a domain name.
  1115. $LINK_DOMAINS = _link_domains();
  1116. $domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)(' . $LINK_DOMAINS . '|[a-z]{2}))/i', $url);
  1117. if (!empty($domain_match)) {
  1118. $url = $protocol . "://" . $url;
  1119. }
  1120. }
  1121. }
  1122. return $url;
  1123. }
  1124. /**
  1125. * Validates a URL.
  1126. *
  1127. * @param $text
  1128. * Url to be validated.
  1129. *
  1130. * @param $langcode
  1131. * An optional language code to look up the path in.
  1132. *
  1133. * @return boolean
  1134. * True if a valid link, FALSE otherwise.
  1135. */
  1136. function link_validate_url($text, $langcode = NULL) {
  1137. $text = link_cleanup_url($text);
  1138. $type = link_url_type($text);
  1139. if ($type && ($type == LINK_INTERNAL || $type == LINK_EXTERNAL)) {
  1140. $flag = valid_url($text, TRUE);
  1141. if (!$flag) {
  1142. $normal_path = drupal_get_normal_path($text, $langcode);
  1143. $parsed_link = parse_url($normal_path, PHP_URL_PATH);
  1144. if ($normal_path != $parsed_link) {
  1145. $normal_path = $parsed_link;
  1146. }
  1147. $flag = drupal_valid_path($normal_path);
  1148. }
  1149. if (!$flag) {
  1150. $flag = file_exists($normal_path);
  1151. }
  1152. if (!$flag) {
  1153. $uri = file_build_uri($normal_path);
  1154. $flag = file_exists($uri);
  1155. }
  1156. }
  1157. else {
  1158. $flag = (bool) $type;
  1159. }
  1160. return $flag;
  1161. }
  1162. /**
  1163. * Type check a URL.
  1164. *
  1165. * Accepts all URLs following RFC 1738 standard for URL formation and all e-mail
  1166. * addresses following the RFC 2368 standard for mailto address formation.
  1167. *
  1168. * @param string $text
  1169. * Url to be checked.
  1170. *
  1171. * @return mixed
  1172. * Returns boolean FALSE if the URL is not valid. On success, returns one of
  1173. * the LINK_(linktype) constants.
  1174. */
  1175. function link_url_type($text) {
  1176. // @TODO Complete letters.
  1177. $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array(
  1178. "&#x00E6;", // æ
  1179. "&#x00C6;", // Æ
  1180. "&#x00C0;", // À
  1181. "&#x00E0;", // à
  1182. "&#x00C1;", // Á
  1183. "&#x00E1;", // á
  1184. "&#x00C2;", // Â
  1185. "&#x00E2;", // â
  1186. "&#x00E5;", // å
  1187. "&#x00C5;", // Å
  1188. "&#x00E4;", // ä
  1189. "&#x00C4;", // Ä
  1190. "&#x00C7;", // Ç
  1191. "&#x00E7;", // ç
  1192. "&#x00D0;", // Ð
  1193. "&#x00F0;", // ð
  1194. "&#x00C8;", // È
  1195. "&#x00E8;", // è
  1196. "&#x00C9;", // É
  1197. "&#x00E9;", // é
  1198. "&#x00CA;", // Ê
  1199. "&#x00EA;", // ê
  1200. "&#x00CB;", // Ë
  1201. "&#x00EB;", // ë
  1202. "&#x00CE;", // Î
  1203. "&#x00EE;", // î
  1204. "&#x00CF;", // Ï
  1205. "&#x00EF;", // ï
  1206. "&#x00F8;", // ø
  1207. "&#x00D8;", // Ø
  1208. "&#x00F6;", // ö
  1209. "&#x00D6;", // Ö
  1210. "&#x00D4;", // Ô
  1211. "&#x00F4;", // ô
  1212. "&#x00D5;", // Õ
  1213. "&#x00F5;", // õ
  1214. "&#x0152;", // Œ
  1215. "&#x0153;", // œ
  1216. "&#x00FC;", // ü
  1217. "&#x00DC;", // Ü
  1218. "&#x00D9;", // Ù
  1219. "&#x00F9;", // ù
  1220. "&#x00DB;", // Û
  1221. "&#x00FB;", // û
  1222. "&#x0178;", // Ÿ
  1223. "&#x00FF;", // ÿ
  1224. "&#x00D1;", // Ñ
  1225. "&#x00F1;", // ñ
  1226. "&#x00FE;", // þ
  1227. "&#x00DE;", // Þ
  1228. "&#x00FD;", // ý
  1229. "&#x00DD;", // Ý
  1230. "&#x00BF;", // ¿
  1231. )), ENT_QUOTES, 'UTF-8');
  1232. $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
  1233. "&#x00DF;", // ß
  1234. )), ENT_QUOTES, 'UTF-8');
  1235. $allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
  1236. $LINK_DOMAINS = _link_domains();
  1237. // Starting a parenthesis group with (?: means that it is grouped, but is not captured.
  1238. $protocol = '((?:' . implode("|", $allowed_protocols) . '):\/\/)';
  1239. $authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w" . $LINK_ICHARS . "\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
  1240. $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*(' . $LINK_DOMAINS . '|[a-z]{2}))?)';
  1241. $ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
  1242. $ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
  1243. $port = '(?::([0-9]{1,5}))';
  1244. // Pattern specific to external links.
  1245. $external_pattern = '/^' . $protocol . '?' . $authentication . '?(' . $domain . '|' . $ipv4 . '|' . $ipv6 . ' |localhost)' . $port . '?';
  1246. // Pattern specific to internal links.
  1247. $internal_pattern = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\] ]+)";
  1248. $internal_pattern_file = "/^(?:[a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \(\)][a-z0-9" . $LINK_ICHARS . "_\-+\[\]\. \/\(\)]+)$/i";
  1249. $directories = "(?:\/[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'#!():;*@\[\]]*)*";
  1250. // Yes, four backslashes == a single backslash.
  1251. $query = "(?:\/?\?([?a-z0-9" . $LINK_ICHARS . "+_|\-\.~\/\\\\%=&,$'!():;*@\[\]{} ]*))";
  1252. $anchor = "(?:#[a-z0-9" . $LINK_ICHARS . "_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
  1253. // The rest of the path for a standard URL.
  1254. $end = $directories . '?' . $query . '?' . $anchor . '?' . '$/i';
  1255. $message_id = '[^@].*@' . $domain;
  1256. $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
  1257. $news_pattern = '/^news:(' . $newsgroup_name . '|' . $message_id . ')$/i';
  1258. $user = '[a-zA-Z0-9' . $LINK_ICHARS . '_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
  1259. $email_pattern = '/^mailto:' . $user . '@' . '(?:' . $domain . '|' . $ipv4 . '|' . $ipv6 . '|localhost)' . $query . '?$/';
  1260. if (strpos($text, '<front>') === 0) {
  1261. return LINK_FRONT;
  1262. }
  1263. if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
  1264. return LINK_EMAIL;
  1265. }
  1266. if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
  1267. return LINK_NEWS;
  1268. }
  1269. if (preg_match($internal_pattern . $end, $text)) {
  1270. return LINK_INTERNAL;
  1271. }
  1272. if (preg_match($external_pattern . $end, $text)) {
  1273. return LINK_EXTERNAL;
  1274. }
  1275. if (preg_match($internal_pattern_file, $text)) {
  1276. return LINK_INTERNAL;
  1277. }
  1278. return FALSE;
  1279. }
  1280. /**
  1281. * Returns the list of allowed domains, including domains added by admins via variable_set/$config.
  1282. */
  1283. function _link_domains() {
  1284. $link_extra_domains = variable_get('link_extra_domains', array());
  1285. return empty($link_extra_domains) ? LINK_DOMAINS : LINK_DOMAINS . '|' . implode('|', $link_extra_domains);
  1286. }
  1287. /**
  1288. * Implements hook_migrate_field_alter().
  1289. */
  1290. function link_content_migrate_field_alter(&$field_value, $instance_value) {
  1291. if ($field_value['type'] == 'link') {
  1292. // Adjust the field type.
  1293. $field_value['type'] = 'link_field';
  1294. // Remove settings that are now on the instance.
  1295. foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
  1296. unset($field_value['settings'][$setting]);
  1297. }
  1298. }
  1299. }
  1300. /**
  1301. * Implements hook_migrate_instance_alter().
  1302. *
  1303. * Widget type also changed to link_field.
  1304. */
  1305. function link_content_migrate_instance_alter(&$instance_value, $field_value) {
  1306. if ($field_value['type'] == 'link') {
  1307. // Grab settings that were previously on the field.
  1308. foreach (array('attributes', 'display', 'url', 'title', 'title_value', 'enable_tokens', 'validate_url') as $setting) {
  1309. if (isset($field_value['settings'][$setting])) {
  1310. $instance_value['settings'][$setting] = $field_value['settings'][$setting];
  1311. }
  1312. }
  1313. // Adjust widget type.
  1314. if ($instance_value['widget']['type'] == 'link') {
  1315. $instance_value['widget']['type'] = 'link_field';
  1316. }
  1317. // Adjust formatter types.
  1318. foreach ($instance_value['display'] as $context => $settings) {
  1319. if (in_array($settings['type'], array('default', 'title_plain', 'url', 'plain', 'short', 'label', 'separate'))) {
  1320. $instance_value['display'][$context]['type'] = 'link_' . $settings['type'];
  1321. }
  1322. }
  1323. }
  1324. }
  1325. /**
  1326. * Implements hook_field_settings_form().
  1327. */
  1328. function link_field_settings_form() {
  1329. return array();
  1330. }
  1331. /**
  1332. * Additional callback to adapt the property info of link fields.
  1333. *
  1334. * @see entity_metadata_field_entity_property_info()
  1335. */
  1336. function link_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  1337. $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];
  1338. // Define a data structure so it's possible to deal with both the link title
  1339. // and URL.
  1340. $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  1341. $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  1342. // Auto-create the field item as soon as a property is set.
  1343. $property['auto creation'] = 'link_field_item_create';
  1344. $property['property info'] = link_field_item_property_info();
  1345. $property['property info']['url']['required'] = !$instance['settings']['url'];
  1346. $property['property info']['title']['required'] = ($instance['settings']['title'] == 'required');
  1347. if ($instance['settings']['title'] == 'none') {
  1348. unset($property['property info']['title']);
  1349. }
  1350. unset($property['query callback']);
  1351. }
  1352. /**
  1353. * Callback for creating a new, empty link field item.
  1354. *
  1355. * @see link_field_property_info_callback()
  1356. */
  1357. function link_field_item_create() {
  1358. return array('title' => NULL, 'url' => NULL);
  1359. }
  1360. /**
  1361. * Defines info for the properties of the link-field item data structure.
  1362. */
  1363. function link_field_item_property_info() {
  1364. $properties['title'] = array(
  1365. 'type' => 'text',
  1366. 'label' => t('The title of the link.'),
  1367. 'setter callback' => 'entity_property_verbatim_set',
  1368. );
  1369. $properties['url'] = array(
  1370. 'type' => 'uri',
  1371. 'label' => t('The URL of the link.'),
  1372. 'setter callback' => 'entity_property_verbatim_set',
  1373. );
  1374. $properties['attributes'] = array(
  1375. 'type' => 'struct',
  1376. 'label' => t('The attributes of the link.'),
  1377. 'setter callback' => 'entity_property_verbatim_set',
  1378. 'getter callback' => 'link_attribute_property_get',
  1379. );
  1380. return $properties;
  1381. }
  1382. /**
  1383. * Entity property info getter callback for link attributes.
  1384. */
  1385. function link_attribute_property_get($data, array $options, $name, $type, $info) {
  1386. return isset($data[$name]) ? array_filter($data[$name]) : array();
  1387. }
  1388. /**
  1389. * Implements hook_field_update_instance().
  1390. */
  1391. function link_field_update_instance($instance, $prior_instance) {
  1392. if (function_exists('i18n_string_update') && $instance['widget']['type'] == 'link_field' && $prior_instance['settings']['title_value'] != $instance['settings']['title_value']) {
  1393. $i18n_string_name = "field:{$instance['field_name']}:{$instance['bundle']}:title_value";
  1394. i18n_string_update($i18n_string_name, $instance['settings']['title_value']);
  1395. }
  1396. }
  1397. /**
  1398. * Implements hook_i18n_string_list_TEXTGROUP_alter().
  1399. */
  1400. function link_i18n_string_list_field_alter(&$strings, $type = NULL, $object = NULL) {
  1401. if ($type != 'field_instance' || !is_array($object) || !isset($object['widget']['type'])) {
  1402. return;
  1403. }
  1404. if ($object['widget']['type'] == 'link_field' && isset($object['settings']['title_value'])) {
  1405. $strings['field'][$object['field_name']][$object['bundle']]['title_value']['string'] = $object['settings']['title_value'];
  1406. }
  1407. }