New module 'Link'

This commit is contained in:
Manuel Cillero 2017-07-26 13:32:46 +02:00
parent 8b1739bd59
commit f0de655d08
16 changed files with 4126 additions and 0 deletions

View file

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View file

@ -0,0 +1,8 @@
div.link-field-column {
float: left;
width: 48%;
}
div.link-field-column .form-text {
width: 95%;
}

View file

@ -0,0 +1,382 @@
<?php
/**
* @file
* Helper functions for Link field, widget and form elements.
*/
function _link_load($field, &$items) {
foreach ($items as $delta => $item) {
// Unserialize the attributes array.
$items[$delta]['attributes'] = unserialize($item['attributes']);
}
return array($field['field_name'] => $items);
}
function _link_process(&$item, $delta = 0, $field, $node) {
// Trim whitespace from URL.
$item['url'] = trim($item['url']);
// if no attributes are set then make sure $item['attributes'] is an empty array - this lets $field['attributes'] override it.
if (empty($item['attributes'])) {
$item['attributes'] = array();
}
// Serialize the attributes array.
$item['attributes'] = serialize($item['attributes']);
// Don't save an invalid default value (e.g. 'http://').
if ((isset($field['widget']['default_value'][$delta]['url']) && $item['url'] == $field['widget']['default_value'][$delta]['url']) && is_object($node)) {
if (!link_validate_url($item['url'])) {
$item['url'] = NULL;
}
}
// If we don't have a title, then set it to null.
if (!isset($item['title'])) {
$item['title'] = NULL;
}
}
function _link_validate(&$item, $delta, $field, $node, &$optional_field_found) {
// neither of these keys are certain to be set
$test = $item + array('url' => NULL, 'title' => NULL);
if ($test['url'] && !(isset($field['widget']['default_value'][$delta]['url']) && $test['url'] == $field['widget']['default_value'][$delta]['url'] && !$field['required'])) {
// Validate the link.
if (link_validate_url(trim($test['url'])) == FALSE) {
form_set_error($field['field_name'] .']['. $delta .'][url', t('Not a valid URL.'));
}
// Require a title for the link if necessary.
if ($field['title'] == 'required' && strlen(trim($test['title'])) == 0) {
form_set_error($field['field_name'] .']['. $delta .'][title', t('Titles are required for all links.'));
}
}
// Require a link if we have a title.
if ((!isset($field['form_id']) || $field['form_id'] != 'content_field_edit_form') && $field['url'] !== 'optional' && strlen($test['title']) > 0 && strlen(trim($test['url'])) == 0) {
form_set_error($field['field_name'] .']['. $delta .'][url', t('You cannot enter a title without a link url.'));
}
// In a totally bizzaro case, where URLs and titles are optional but the field is required, ensure there is at least one link.
if ($field['url'] == 'optional' && $field['title'] == 'optional' && (strlen(trim($test['url'])) != 0 || strlen(trim($test['title'])) != 0)) {
$optional_field_found = TRUE;
}
}
/**
* Cleanup user-entered values for a link field according to field settings.
*
* @param $item
* A single link item, usually containing url, title, and attributes.
* @param $delta
* The delta value if this field is one of multiple fields.
* @param $field
* The CCK field definition.
* @param $node
* The node containing this link.
*/
function _link_sanitize(&$item, $delta, &$field, &$node) {
// Don't try to process empty links.
if (empty($item['url']) && empty($item['title']) && empty($field['title_value'])) {
return;
}
// Replace URL tokens.
if ($field['enable_tokens'] && module_exists('token')) {
// Load the node if necessary for nodes in views.
$token_node = isset($node->nid) ? node_load($node->nid) : $node;
$item['url'] = token_replace($item['url'], 'node', $token_node);
}
$type = link_validate_url($item['url']);
// If we can't determine the type of url, and we've been told not to validate it,
// then we assume it's a LINK_EXTERNAL type for later processing. #357604
if ($type == FALSE && $field['validate_url'] === 0) {
$type = LINK_EXTERNAL;
}
$url = link_cleanup_url($item['url']);
// Separate out the anchor if any.
if (strpos($url, '#') !== FALSE) {
$item['fragment'] = substr($url, strpos($url, '#') + 1);
$url = substr($url, 0, strpos($url, '#'));
}
// Separate out the query string if any.
if (strpos($url, '?') !== FALSE) {
$item['query'] = substr($url, strpos($url, '?') + 1);
$url = substr($url, 0, strpos($url, '?'));
}
// Save the new URL without the anchor or query.
if ($field['validate_url'] === 0) {
$item['url'] = check_plain($url);
}
else {
$item['url'] = $url;
}
// Create a shortened URL for display.
$display_url = $type == LINK_EMAIL ? str_replace('mailto:', '', $url) : url($url, array('query' => isset($item['query']) ? $item['query'] : NULL, 'fragment' => isset($item['fragment']) ? $item['fragment'] : NULL, 'absolute' => TRUE));
if (is_array($field['display']) && !empty($field['display']['url_cutoff']) && strlen($display_url) > $field['display']['url_cutoff']) {
$display_url = substr($display_url, 0, $field['display']['url_cutoff']) ."...";
}
$item['display_url'] = $display_url;
// Use the title defined at the field level.
if ($field['title'] == 'value' && strlen(trim($field['title_value']))) {
$title = $field['title_value'];
}
// Use the title defined by the user at the widget level.
else {
$title = $item['title'];
}
// Replace tokens. - originally we only did it for value titles.
if (($field['title'] == 'value' || $field['enable_tokens']) && module_exists('token')) {
// Load the node if necessary for nodes in views.
$token_node = isset($node->nid) ? node_load($node->nid) : $node;
$title = filter_xss(token_replace($title, 'node', $token_node), array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
$item['html'] = TRUE;
}
elseif ($field['title'] == 'value') {
$title = filter_xss($title, array('b', 'br', 'code', 'em', 'i', 'img', 'span', 'strong', 'sub', 'sup', 'tt', 'u'));
$item['html'] = TRUE;
}
$item['display_title'] = empty($title) ? $item['display_url'] : $title;
if (!isset($item['attributes'])) {
$item['attributes'] = array();
}
// Unserialize attributtes array if it has not been unserialized yet.
if (!is_array($item['attributes'])) {
$item['attributes'] = (array)unserialize($item['attributes']);
}
// Add default attributes. Make sure that $field['attributes'] is an array. #626932
if (!is_array($field['attributes'])) {
$field['attributes'] = array();
}
$field['attributes'] += _link_default_attributes();
// Merge item attributes with attributes defined at the field level.
$item['attributes'] = array_filter($item['attributes']);
$item['attributes'] += $field['attributes'];
if (empty($item['attributes'])) {
unset($item['attributes']['target']);
}
switch ($field['attributes']['target']) {
case LINK_TARGET_DEFAULT:
unset($item['attributes']['target']);
break;
case LINK_TARGET_USER:
// '_blank' is the only authorized value for target in this version.
if ($item['attributes']['target'] != '_blank') {
unset($item['attributes']['target']);
}
break;
default: // LINK_TARGET_NEW_WINDOW and LINK_TARGET_TOP
$item['attributes']['target'] = $field['attributes']['target'];
break;
}
// Remove the rel=nofollow for internal links.
if ($type != LINK_EXTERNAL && $type != LINK_NEWS && strpos($item['attributes']['rel'], 'nofollow') !== FALSE) {
$item['attributes']['rel'] = str_replace('nofollow', '', $item['attributes']['rel']);
}
// Some old field data may have $item['#item']['attributes']['rel'] as an array, which will cause errors:
if (isset($item['#item']['attributes']['rel']) && is_array($item['#item']['attributes']['rel'])) {
unset($item['#item']['attributes']['rel']);
}
// Handle "title" link attribute
if (!empty($item['attributes']['title']) && module_exists('token')) {
// Load the node (necessary for nodes in views).
$token_node = isset($node->nid) ? node_load($node->nid) : $node;
$item['attributes']['title'] = token_replace($item['attributes']['title'], 'node', $token_node);
}
// Remove title attribute if it's equal to link text.
if ($item['attributes']['title'] == $item['display_title']) {
unset($item['attributes']['title']);
}
// Hide the display title the URL is empty and the "Hide title if URL is
// empty" has been checked.
if (empty($item['url']) && isset($field['title_value_visibility']) && $field['title_value_visibility'] == 1) {
unset($item['display_title']);
}
// Remove empty attributes.
$item['attributes'] = array_filter($item['attributes']);
// Add the widget label.
$item['label'] = $field['widget']['label'];
}
function _link_default_attributes() {
return array(
'title' => '',
'target' => LINK_TARGET_DEFAULT,
'class' => '',
'rel' => '',
);
}
/**
* Forms a valid URL if possible from an entered address.
* Trims whitespace and automatically adds an http:// to addresses without a protocol specified
*
* @param string $url
* @param string $protocol The protocol to be prepended to the url if one is not specified
*/
function link_cleanup_url($url, $protocol = "http") {
$url = trim($url);
$type = link_validate_url($url);
if ($type == LINK_EXTERNAL) {
// Check if there is no protocol specified.
$protocol_match = preg_match("/^([a-z0-9][a-z0-9\.\-_]*:\/\/)/i", $url);
if (empty($protocol_match)) {
// But should there be? Add an automatic http:// if it starts with a domain name.
$domain_match = preg_match('/^(([a-z0-9]([a-z0-9\-_]*\.)+)('. LINK_DOMAINS .'|[a-z]{2}))/i', $url);
if (!empty($domain_match)) {
$url = $protocol ."://". $url;
}
}
}
return $url;
}
/**
* Wrapper around html_entity_decode to handle problems with PHP 4.
*
* See http://drupal.org/node/739650
* See http://bugs.php.net/bug.php?id=25670
*
* We've taken this away from the beginning of file define() step, as this is
* going to be slower for PHP4, and we don't want to run this on every page load,
* just when we're doing a validate.
*/
function _link_html_entity_decode($html_string, $quote_style = ENT_COMPAT, $charset) {
if (defined('PHP_VERSION')) {
$version = explode('.', PHP_VERSION);
if ($version[0] == '5') {
return html_entity_decode($html_string, $quote_style, $charset); // PHP 5, use default.
}
}
else {
$version = explode('.', PHP_VERSION);
if ($version[0] == '5') {
return html_entity_decode($html_string, $quote_style, $charset);
}
}
// use suggested code from http://drupal.org/node/739650
// replace numeric entities
$string = preg_replace('~&#x([0-9a-f]+);~ei', "_link_code2utf(hexdec('\\1'))", $html_string);
$string = preg_replace('~&#([0-9]+);~e', '_link_code2utf("\\1")', $string);
// replace literal entities.
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
return strtr($string, $trans_tbl);
}
/**
* Returns the utf string corresponding to the unicode value.
*
* Needed for handling utf characters in PHP4.
*
* @see http://www.php.net/manual/en/function.html-entity-decode.php#75153
*/
function _link_code2utf($num) {
if ($num < 128) return chr($num);
if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
return '';
}
/**
* A lenient verification for URLs. Accepts all URLs following RFC 1738 standard
* for URL formation and all email addresses following the RFC 2368 standard for
* mailto address formation.
*
* @param string $text
* @return mixed Returns boolean FALSE if the URL is not valid. On success, returns an object with
* the following attributes: protocol, hostname, ip, and port.
*/
function link_validate_url($text) {
$LINK_ICHARS_DOMAIN = (string) _link_html_entity_decode(implode("", array(
"&#x00E6;", // æ
"&#x00C6;", // Æ
"&#x00F8;", // ø
"&#x00D8;", // Ø
"&#x00E5;", // å
"&#x00C5;", // Å
"&#x00E4;", // ä
"&#x00C4;", // Ä
"&#x00F6;", // ö
"&#x00D6;", // Ö
"&#x00FC;", // ü
"&#x00DC;", // Ü
"&#x00D1;", // Ñ
"&#x00F1;", // ñ
)), ENT_QUOTES, 'UTF-8');
$LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) _link_html_entity_decode(implode("", array(
"&#x00DF;", // ß
)), ENT_QUOTES, 'UTF-8');
$allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
$protocol = '(('. implode("|", $allowed_protocols) .'):\/\/)';
$authentication = '(([a-z0-9%' . $LINK_ICHARS . ']+(:[a-z0-9%'. $LINK_ICHARS . '!]*)?)?@)';
$domain = '(([a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*('. LINK_DOMAINS .'|[a-z]{2}))?)';
$ipv4 = '([0-9]{1,3}(\.[0-9]{1,3}){3})';
$ipv6 = '([0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
$port = '(:([0-9]{1,5}))';
// Pattern specific to external links.
$external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';
// Pattern specific to internal links.
$internal_pattern = "/^([a-z0-9". $LINK_ICHARS ."_\-+\[\]]+)";
$internal_pattern_file = "/^([a-z0-9". $LINK_ICHARS ."_\-+\[\]\.]+)$/i";
$directories = "(\/[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'!():;*@\[\]]*)*";
// Yes, four backslashes == a single backslash.
$query = "(\/?\?([?a-z0-9". $LINK_ICHARS ."+_|\-\.\/\\\\%=&,$'():;*@\[\]{} ]*))";
$anchor = "(#[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'():;*@\[\]\/\?]*)";
// The rest of the path for a standard URL.
$end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';
$message_id = '[^@].*@'. $domain;
$newsgroup_name = '([0-9a-z+-]*\.)*[0-9a-z+-]*';
$news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';
$user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
$email_pattern = '/^mailto:'. $user .'@'.'('. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';
if (strpos($text, '<front>') === 0) {
return LINK_FRONT;
}
if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
return LINK_EMAIL;
}
if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
return LINK_NEWS;
}
if (preg_match($internal_pattern . $end, $text)) {
return LINK_INTERNAL;
}
if (preg_match($external_pattern . $end, $text)) {
return LINK_EXTERNAL;
}
if (preg_match($internal_pattern_file, $text)) {
return LINK_INTERNAL;
}
return FALSE;
}

View file

@ -0,0 +1,14 @@
name = Link
description = Defines simple link field types.
dependencies[] = content
package = CCK
core = 6.x
files[] = link.migrate.inc
; Information added by Drupal.org packaging script on 2014-02-28
version = "6.x-2.11"
core = "6.x"
project = "link"
datestamp = "1393559923"

View file

@ -0,0 +1,137 @@
<?php
/**
* @file
* Install file for the link module.
*/
/**
* Implementation of hook_install().
*/
function link_install() {
drupal_load('module', 'content');
content_notify('install', 'link');
}
/**
* Implementation of hook_uninstall().
*/
function link_uninstall() {
drupal_load('module', 'content');
content_notify('uninstall', 'link');
}
/**
* Implementation of hook_enable().
*/
function link_enable() {
drupal_load('module', 'content');
content_notify('enable', 'link');
}
/**
* Implementation of hook_disable().
*/
function link_disable() {
drupal_load('module', 'content');
content_notify('disable', 'link');
}
/**
* Removed link.module created tables, move data to content.module tables
*
* Even though most everyone will not be using this particular update, several
* folks have complained that their upgrades of link.module do not work because
* of this function being missing when schema expects it. - JCF
* And on further review, I'm removing the body, since some of those calls
* no longer exist in Drupal 6. Remember to upgrade from 4.7 to 5 first, and
* *then* from 5 to 6. kthx! -JCF
*/
function link_update_1() {
$ret = array();
// GNDN
return $ret;
}
/**
* Ensure that content.module is updated before link module.
*/
function link_update_6000() {
if ($abort = content_check_update('link')) {
return $abort;
}
return array();
}
/**
* Change the database schema to allow NULL values.
*/
function link_update_6001() {
$ret = array();
// Build a list of fields that need updating.
$update_fields = array();
foreach (content_types_install() as $type_name => $fields) {
foreach ($fields as $field) {
if ($field['type'] == 'link') {
// We only process a given field once.
$update_fields[$field['field_name']] = $field;
}
}
}
// Update each field's storage to match the current definition.
foreach ($update_fields as $field) {
$db_info = content_database_info($field);
foreach ($db_info['columns'] as $column) {
db_change_field($ret, $db_info['table'], $column['column'], $column['column'], $column);
$ret[] = update_sql("UPDATE {". $db_info['table'] ."} SET ". $column['column'] ." = NULL WHERE ". $column['column'] ." = '' OR ". $column['column'] ." = 'N;'");
}
}
// Let CCK re-associate link fields with Link module and activate the fields.
content_associate_fields('link');
return $ret;
}
/**
* 6.x-2.7 had code that mistakenly wrote 'a:3:{s:6:"target";s:7:"default";s:5:"class";s:0:"";s:3:"rel";s:0:"";}'
* to the attributes field, when it should have written NULL.
*
* This fixes that. Ticket #626932.
*/
function link_update_6002() {
$ret = array();
// Build a list of fields that need updating.
$update_fields = array();
foreach (content_types_install() as $type_name => $fields) {
foreach ($fields as $field) {
if ($field['type'] == 'link') {
// We only process a given field once.
$update_fields[$field['field_name']] = $field;
}
}
}
// Update each field's storage to match the current definition.
foreach ($update_fields as $field) {
$db_info = content_database_info($field);
foreach ($db_info['columns'] as $column) {
//db_change_field($ret, $db_info['table'], $column['column'], $column['column'], $column);
if (preg_match('/_attributes$/', $column['column'])) {
//we can't use update_sql, because it doesn't handle serialized data.
$sql = "UPDATE {". $db_info['table'] ."} SET ". $column['column'] ." = NULL WHERE ". $column['column'] ." = '%s'";
$result = db_query($sql, 'a:3:{s:6:"target";s:7:"default";s:5:"class";s:0:"";s:3:"rel";s:0:"";}');
$ret[] = array('success' => $result !== FALSE, 'query' => check_plain($sql));
}
}
}
// Let CCK re-associate link fields with Link module and activate the fields.
content_associate_fields('link');
return $ret;
}

View file

@ -0,0 +1,51 @@
<?php
/**
* @file
* Support for migrate module
*/
class MigrateLinkFieldHandler extends MigrateFieldHandler {
public function __construct() {
$this->registerTypes(array('link'));
}
static function arguments($title = NULL, $attributes = NULL, $language = NULL) {
$arguments = array();
if (!is_null($title)) {
$arguments['title'] = $title;
}
if (!is_null($attributes)) {
$arguments['attributes'] = $attributes;
}
if (!is_null($language)) {
$arguments['language'] = $language;
}
return $arguments;
}
public function prepare($entity, array $instance, array $values) {
if (isset($values['arguments'])) {
$arguments = $values['arguments'];
unset($values['arguments']);
}
else {
$arguments = array();
}
$delta = 0;
foreach($values as $value) {
$item = array();
if (isset($arguments['title'])) {
$item['title'] = $arguments['title'];
}
if (isset($arguments['attributes'])) {
$item['attributes'] = $arguments['attributes'];
}
$item['url'] = $value;
$return[$delta] = $item;
$delta++;
}
return isset($return) ? $return : NULL;
}
}

View file

@ -0,0 +1,501 @@
<?php
/**
* @file
* Defines simple link field types.
*/
define('LINK_EXTERNAL', 'external');
define('LINK_INTERNAL', 'internal');
define('LINK_FRONT', 'front');
define('LINK_EMAIL', 'email');
define('LINK_NEWS', 'news');
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');
// There are many other characters which are legal other than simply a-z - this includes them.
// html_entity_decode() is buggy in php 4 - we'll put it back here for D7 when 5.x is assumed.
/*define('LINK_ICHARS', (string) html_entity_decode(implode("", array(
"&#x00E6;", // æ
"&#x00C6;", // Æ
"&#x00F8;", // ø
"&#x00D8;", // Ø
"&#x00E5;", // å
"&#x00C5;", // Å
"&#x00E4;", // ä
"&#x00C4;", // Ä
"&#x00F6;", // ö
"&#x00D6;", // Ö
"&#x00FC;", // ü
"&#x00DC;", // Ü
)), ENT_QUOTES, 'UTF-8'));*/
define('LINK_TARGET_DEFAULT', 'default');
define('LINK_TARGET_NEW_WINDOW', '_blank');
define('LINK_TARGET_TOP', '_top');
define('LINK_TARGET_USER', 'user');
/**
* Maximum URLs length.
*/
define('LINK_URL_MAX_LENGTH', 2048);
/**
* Implementation of hook_field_info().
*/
function link_field_info() {
return array(
'link' => array(
'label' => t('Link'),
'description' => t('Store a title, href, and attributes in the database to assemble a link.'),
),
);
}
/**
* Implementation of hook_field_settings().
*/
function link_field_settings($op, $field) {
switch ($op) {
case 'form':
$form = array(
'#theme' => 'link_field_settings',
);
$form['validate_url'] = array(
'#type' => 'checkbox',
'#title' => t('Validate URL'),
'#default_value' => isset($field['validate_url']) && ($field['validate_url'] !== '') ? $field['validate_url'] : TRUE,
'#description' => t('If checked, the URL field will be verified as a valid URL during validation.'),
);
$form['url'] = array(
'#type' => 'checkbox',
'#title' => t('Optional URL'),
'#default_value' => $field['url'],
'#return_value' => 'optional',
'#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.'),
);
$title_options = array(
'optional' => t('Optional Title'),
'required' => t('Required Title'),
'value' => t('Static Title: '),
'none' => t('No Title'),
);
$form['title'] = array(
'#type' => 'radios',
'#title' => t('Link Title'),
'#default_value' => isset($field['title']) && ($field['title'] !== '') ? $field['title'] : 'optional',
'#options' => $title_options,
'#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 node 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.'),
);
$form['title_value'] = array(
'#type' => 'textfield',
'#default_value' => $field['title_value'],
'#size' => '46',
);
$form['title_value_visibility'] = array(
'#type' => 'checkbox',
'#title' => t('Hide title if URL is empty'),
'#default_value' => isset($field['title_value_visibility']) ? $field['title_value_visibility'] : 0,
'#description' => t('Checking will hide the title when a URL is empty, leave un-checked to always display the title.'),
);
// Add token module replacements if available
if (module_exists('token')) {
$form['tokens'] = array(
'#type' => 'fieldset',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#title' => t('Placeholder tokens'),
'#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."),
);
$form['tokens']['help'] = array(
'#value' => theme('token_help', 'node'),
);
$form['enable_tokens'] = array(
'#type' => 'checkbox',
'#title' => t('Allow user-entered tokens'),
'#default_value' => isset($field['enable_tokens']) ? $field['enable_tokens'] : 1,
'#description' => t('Checking will allow users to enter tokens in URLs and Titles on the node edit form. This does not affect the field settings on this page.'),
);
}
$form['display'] = array(
'#tree' => TRUE,
);
$form['display']['url_cutoff'] = array(
'#type' => 'textfield',
'#title' => t('URL Display Cutoff'),
'#default_value' => isset($field['display']['url_cutoff']) ? $field['display']['url_cutoff'] : '80',
'#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.'),
'#maxlength' => 3,
'#size' => 3,
);
$target_options = array(
LINK_TARGET_DEFAULT => t('Default (no target attribute)'),
LINK_TARGET_TOP => t('Open link in window root'),
LINK_TARGET_NEW_WINDOW => t('Open link in new window'),
LINK_TARGET_USER => t('Allow the user to choose'),
);
$form['attributes'] = array(
'#tree' => TRUE,
);
$form['attributes']['target'] = array(
'#type' => 'radios',
'#title' => t('Link Target'),
'#default_value' => empty($field['attributes']['target']) ? LINK_TARGET_DEFAULT : $field['attributes']['target'],
'#options' => $target_options,
);
$form['attributes']['rel'] = array(
'#type' => 'textfield',
'#title' => t('Rel Attribute'),
'#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.'),
'#default_value' => empty($field['attributes']['rel']) ? '' : $field['attributes']['rel'],
'#field_prefix' => 'rel = "',
'#field_suffix' => '"',
'#size' => 20,
);
$form['attributes']['class'] = array(
'#type' => 'textfield',
'#title' => t('Additional CSS Class'),
'#description' => t('When output, this link will have this class attribute. Multiple classes should be separated by spaces.'),
'#default_value' => empty($field['attributes']['class']) ? '' : $field['attributes']['class'],
);
$form['attributes']['title'] = array(
'#title' => t("Link 'title' Attribute"),
'#type' => 'textfield',
'#field_prefix' => 'title = "',
'#field_suffix' => '"',
'#description' => t('When output, links will use this "title" attribute (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.'),
'#default_value' => empty($field['attributes']['title']) ? '' : $field['attributes']['title'],
);
return $form;
case 'validate':
if ($field['title'] == 'value' && empty($field['title_value'])) {
form_set_error('title_value', t('A default title must be provided if the title is a static value'));
}
break;
case 'save':
return array('attributes', 'display', 'url', 'title', 'title_value', 'title_value_visibility', 'enable_tokens', 'validate_url');
case 'database columns':
return array(
'url' => array('type' => 'varchar', 'length' => LINK_URL_MAX_LENGTH, 'not null' => FALSE, 'sortable' => TRUE),
'title' => array('type' => 'varchar', 'length' => 255, 'not null' => FALSE, 'sortable' => TRUE),
'attributes' => array('type' => 'text', 'size' => 'medium', 'not null' => FALSE),
);
case 'views data':
module_load_include('inc', 'link', 'views/link.views');
return link_views_content_field_data($field);
}
}
/**
* Implementation of hook_content_is_empty().
*/
function link_content_is_empty($item, $field) {
if (empty($item['title']) && empty($item['url'])) {
return TRUE;
}
return FALSE;
}
/**
* Implementation of hook_field().
*/
function link_field($op, &$node, $field, &$items, $teaser, $page) {
module_load_include('inc', 'link');
switch ($op) {
case 'load':
return _link_load($field, $items);
case 'validate':
$optional_field_found = FALSE;
if ($field['validate_url'] !== 0 || is_null($field['validate_url']) || !isset($field['validate_url'])) {
foreach ($items as $delta => $value) {
_link_validate($items[$delta], $delta, $field, $node, $optional_field_found);
}
}
if ($field['url'] === 'optional' && $field['title'] === 'optional' && $field['required'] && !$optional_field_found) {
form_set_error($field['field_name'] .'][0][title', t('At least one title or URL must be entered.'));
}
break;
case 'presave':
case 'update':
foreach ($items as $delta => $value) {
_link_process($items[$delta], $delta, $field, $node);
}
break;
case 'sanitize':
foreach ($items as $delta => $value) {
_link_sanitize($items[$delta], $delta, $field, $node);
}
break;
}
}
/**
* Implementation of hook_widget_info().
*/
function link_widget_info() {
return array(
'link' => array(
'label' => 'Link',
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
);
}
/**
* Implementation of hook_widget().
*/
function link_widget(&$form, &$form_state, $field, $items, $delta = 0) {
$element = array(
'#type' => $field['widget']['type'],
'#default_value' => isset($items[$delta]) ? $items[$delta] : '',
'#title' => $field['widget']['label'],
'#weight' => $field['widget']['weight'],
'#description' => $field['widget']['description'],
'#required' => $field['required'],
'#field' => $field,
);
return $element;
}
/**
* Implementation of hook_theme().
*/
function link_theme() {
return array(
'link_field_settings' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_default' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_plain' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_absolute' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_title_plain' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_url' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_short' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_label' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link_formatter_separate' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
'link' => array(
'arguments' => array('element' => NULL),
'file' => 'link.theme.inc',
),
);
}
/**
* Implementation of hook_elements().
*/
function link_elements() {
$elements = array();
$elements['link'] = array(
'#input' => TRUE,
'#process' => array('link_process'),
);
return $elements;
}
/**
* Process the link type element before displaying the field.
*
* Build the form element. When creating a form using FAPI #process,
* note that $element['#value'] is already set.
*
* The $fields array is in $form['#field_info'][$element['#field_name']].
*/
function link_process($element, $edit, $form_state, $form) {
module_load_include('inc', 'link');
$field = $form['#field_info'][$element['#field_name']];
$delta = $element['#delta'];
$element['url'] = array(
'#type' => 'textfield',
'#maxlength' => LINK_URL_MAX_LENGTH,
'#title' => t('URL'),
'#description' => $element['#description'],
'#required' => ($delta == 0 && $field['url'] !== 'optional') ? $element['#required'] : FALSE,
'#default_value' => isset($element['#value']['url']) ? $element['#value']['url'] : NULL,
);
if ($field['title'] != 'none' && $field['title'] != 'value') {
$element['title'] = array(
'#type' => 'textfield',
'#maxlength' => '255',
'#title' => t('Title'),
'#required' => ($delta == 0 && $field['title'] == 'required') ? $field['required'] : FALSE,
'#default_value' => isset($element['#value']['title']) ? $element['#value']['title'] : NULL,
);
}
// Initialize field attributes as an array if it is not an array yet.
if (!is_array($field['attributes'])) {
$field['attributes'] = array();
}
// Add default atrributes.
$field['attributes'] += _link_default_attributes();
$attributes = isset($element['#value']['attributes']) ? $element['#value']['attributes'] : $field['attributes'];
if (!empty($field['attributes']['target']) && $field['attributes']['target'] == LINK_TARGET_USER) {
$element['attributes']['target'] = array(
'#type' => 'checkbox',
'#title' => t('Open URL in a New Window'),
'#return_value' => LINK_TARGET_NEW_WINDOW,
'#default_value' => $attributes['target'],
);
}
return $element;
}
/**
* Implementation of hook_field_formatter_info().
*/
function link_field_formatter_info() {
return array(
'default' => array(
'label' => t('Title, as link (default)'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'title_plain' => array(
'label' => t('Title, as plain text'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'url' => array(
'label' => t('URL, as link'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'plain' => array(
'label' => t('URL, as plain text'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'absolute' => array(
'label' => t('URL, as absolute URL'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'short' => array(
'label' => t('Short, as link with title "Link"'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'label' => array(
'label' => t('Label, as link with label as title'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
'separate' => array(
'label' => t('Separate title and URL'),
'field types' => array('link'),
'multiple values' => CONTENT_HANDLE_CORE,
),
);
}
function link_token_list($type = 'all') {
if ($type == 'field' || $type == 'all') {
$tokens = array();
$tokens['link']['url'] = t("Link URL");
$tokens['link']['title'] = t("Link title");
$tokens['link']['view'] = t("Formatted html link");
$tokens['link']['host'] = t("Link host");
return $tokens;
}
}
function link_token_values($type, $object = NULL) {
if ($type == 'field') {
$item = $object[0];
$tokens['url'] = $item['url'];
$tokens['title'] = $item['title'];
$tokens['view'] = isset($item['view']) ? $item['view'] : '';
$host = @parse_url($item['url']);
$tokens['host'] = isset($host['host']) ? $host['host'] : '';
return $tokens;
}
}
/**
* Implementation of hook_views_api().
*/
function link_views_api() {
return array(
'api' => 2,
'path' => drupal_get_path('module', 'link') .'/views',
);
}
/**
* Implements hook_migrate_api().
*/
function link_migrate_api() {
return array('api' => 2);
}
/**
* Implements hook_content_generate().
*/
function link_content_generate($node, $field) {
if (content_handle('widget', 'multiple values', $field) == CONTENT_HANDLE_MODULE) {
return content_devel_multiple('_link_content_generate', $node, $field);
}
else {
return _link_content_generate($node, $field);
}
}
/**
* Generates random link data for devel generate.
*/
function _link_content_generate($node, $field) {
// Have to use title = true to get only one word, but then want to force it to lowercase.
$url = url('http://www.example.com/' . drupal_strtolower(devel_create_greeking(1, TRUE)));
$title = devel_create_greeking(mt_rand(1, 3), TRUE);
return array(
'url' => $url,
'title' => $title,
'attributes' => array(),
);
}

View file

@ -0,0 +1,130 @@
<?php
/**
* @file
* Theme functions for the link module.
*/
/**
* Theme the settings form for the link field.
*/
function theme_link_field_settings($form) {
$title_value = drupal_render($form['title_value']);
$title_checkbox = drupal_render($form['title']['value']);
// Set Static Title radio option to include the title_value textfield.
$form['title']['value'] = array('#value' => '<div class="container-inline">'. $title_checkbox . $title_value .'</div>');
// Reprint the title radio options with the included textfield.
return drupal_render($form);
}
/**
* FAPI theme for an individual text elements.
*/
function theme_link($element) {
drupal_add_css(drupal_get_path('module', 'link') .'/link.css');
// Prefix single value link fields with the name of the field.
if (empty($element['#field']['multiple'])) {
if (isset($element['url']) && isset($element['title'])) {
$element['url']['#title'] = $element['#title'] .' '. $element['url']['#title'];
$element['title']['#title'] = $element['#title'] .' '. $element['title']['#title'];
}
elseif ($element['url']) {
$element['url']['#title'] = $element['#title'];
}
}
$output = '';
$output .= '<div class="link-field-subrow clear-block">';
if (isset($element['title'])) {
$output .= '<div class="link-field-title link-field-column">'. theme('textfield', $element['title']) .'</div>';
}
$output .= '<div class="link-field-url'. (isset($element['title']) ? ' link-field-column' : '') .'">'. theme('textfield', $element['url']) .'</div>';
$output .= '</div>';
if (!empty($element['attributes']['target'])) {
$output .= '<div class="link-attributes">'. theme('checkbox', $element['attributes']['target']) .'</div>';
}
return $output;
}
/**
* Theme function for 'default' text field formatter.
*/
function theme_link_formatter_default($element) {
// Display a normal link if both title and URL are available.
if (!empty($element['#item']['display_title']) && !empty($element['#item']['url'])) {
return l($element['#item']['display_title'], $element['#item']['url'], $element['#item']);
}
// If no title, no url, display nothing.
elseif (empty($element['#item']['title']) && empty($element['#item']['url'])) {
return ;
}
// If only a title, display the title.
elseif (!empty($element['#item']['display_title'])) {
return check_plain($element['#item']['display_title']);
}
}
/**
* Theme function for 'plain' text field formatter.
*/
function theme_link_formatter_plain($element) {
return empty($element['#item']['url']) ? check_plain($element['#item']['title']) : url($element['#item']['url'], $element['#item']);
}
/**
* Theme function for 'absolute' link field formatter.
*/
function theme_link_formatter_absolute($element) {
$absolute = array('absolute' => TRUE);
return empty($element['#item']['url']) ? '' : url($element['#item']['url'], $absolute + $element['#item']);
}
/**
* Theme function for 'title_plain' text field formatter.
*/
function theme_link_formatter_title_plain($element) {
return empty($element['#item']['title']) ? '' : check_plain($element['#item']['title']);
}
/**
* Theme function for 'url' text field formatter.
*/
function theme_link_formatter_url($element) {
return $element['#item']['url'] ? l($element['#item']['display_url'], $element['#item']['url'], $element['#item']) : '';
}
/**
* Theme function for 'short' text field formatter.
*/
function theme_link_formatter_short($element) {
return $element['#item']['url'] ? l(t('Link'), $element['#item']['url'], $element['#item']) : '';
}
/**
* Theme function for 'label' text field formatter.
*/
function theme_link_formatter_label($element) {
return $element['#item']['url'] ? l($element['#item']['label'], $element['#item']['url'], $element['#item']) : '';
}
/**
* Theme function for 'separate' text field formatter.
*/
function theme_link_formatter_separate($element) {
$class = empty($element['#item']['attributes']['class']) ? '' : ' '. $element['#item']['attributes']['class'];
unset($element['#item']['attributes']['class']);
$title = empty($element['#item']['title']) ? '' : check_plain($element['#item']['title']);
$output = '';
$output .= '<div class="link-item '. $class .'">';
if (!empty($title)) {
$output .= '<div class="link-title">'. $title .'</div>';
}
$output .= '<div class="link-url">'. l($element['#item']['display_url'], $element['#item']['url'], $element['#item']) .'</div>';
$output .= '</div>';
return $output;
}

View file

@ -0,0 +1,764 @@
<?php
/**
* @file
* Basic simpletests to test options on link module.
*/
// Let's include the parent class.
module_load_include('test', 'content', 'tests/content.crud');
class LinkAttributeCrudTest extends ContentCrudTestCase {
private $zebra;
public $permissions = array(
'access content',
'administer content types',
'administer nodes',
'administer filters',
'access comments',
'post comments',
'post comments without approval',
'access administration pages',
);
function getInfo() {
return array(
'name' => t('Link Attribute Tests'),
'description' => t('Tests the field attributes, making sure they appear in various displayed situations.'),
'group' => t('Link'),
);
}
function setUp() {
$this->zebra = 0;
parent::setUp('link');
$this->loginWithPermissions($this->permissions);
}
function createLink($url, $title, $attributes = array()) {
return array(
'url' => $url,
'title' => $title,
'attributes' => $attributes,
);
}
/**
* This usually isn't needed. $this->pass($this->content); will usually
* display the current page.
*/
private function outputScreenContents($description, $basename) {
// This is a hack to get a directory that won't be cleaned up by simpletest
$file_dir = file_directory_path() .'/../simpletest_output_pages';
if (!is_dir($file_dir)) {
mkdir($file_dir, 0777, TRUE);
}
$output_path = "$file_dir/$basename." . $this->randomName(10) . '.html';
$rv = file_put_contents($output_path, $this->drupalGetContent());
$this->pass("$description: Contents of result page are ". l('here', $output_path));
}
private function assertLinkOnNode($field_name, $link_value, $message = '', $group = 'Other') {
$this->zebra++;
$zebra_string = ($this->zebra % 2 == 0) ? 'even' : 'odd';
$cssFieldLocator = 'field-'. str_replace('_', '-', $field_name);
$this->assertPattern('@<div class="field field-type-link '. $cssFieldLocator .'".*<div class="field-item '. $zebra_string .'">\s*'. $link_value .'\s*</div>@is',
$message,
$group);
}
/**
* A simple test that just creates a new node type, adds a link field to it, creates a new node of that type, and makes sure
* that the node is being displayed.
*/
function testBasic() {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error.
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('http://www.example.com', 'Test Link');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com'));
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com'));
}
/**
* This test sees that we can create a link field with a defined class, and make sure
* that class displays properly when the link is displayed.
*/
function testLinkWithClassOnField() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => 'test-class',
'target' => 'default',
'rel' => FALSE,
),
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('http://www.example.com', 'Test Link');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
//$this->outputScreenContents('Link field with class', 'link_');
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('class' => 'test-class'))));
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('class' => 'test-class'))));
}
function testLinkWithNoFollowOnField() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
),
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('http://www.example.com', 'Test Link');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
//$this->outputScreenContents('Link field with class', 'link_');
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('rel' => 'nofollow'))));
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('rel' => 'nofollow'))));
}
function testLinkWithNoFollowOnFieldTargetNewWindow() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => LINK_TARGET_NEW_WINDOW,
'rel' => 'nofollow',
),
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('http://www.example.com', 'Test Link');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
//$this->outputScreenContents('Link field with class', 'link_');
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('target' => '_blank', 'rel' => 'nofollow'))));
//$this->pass($this->content);
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('target' => '_blank', 'rel' => 'nofollow'))));
}
/**
* Trying to reproduce exactly what's in issue #664990
*
* http://drupal.org/node/664990
*/
function testLinkWithNoFollowOnFieldTargetNewWindowAndAClass() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => 'testlink',
'target' => LINK_TARGET_NEW_WINDOW,
'rel' => 'nofollow',
),
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('http://www.example.com', 'Test Link');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
//$this->outputScreenContents('Link field with class', 'link_');
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('class' => 'testlink', 'target' => '_blank', 'rel' => 'nofollow'))));
//$this->pass($this->content);
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com', array('attributes' => array('class' => 'testlink', 'target' => '_blank', 'rel' => 'nofollow'))));
}
/**
* Another test for http://drupal.org/node/664990
*/
function test_Link_With_Title_Attribute_WithNoFollowOnFieldTargetNewWindowAndAClass_Form() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$field = $this->createField($field_settings, 0);
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
$edit = array();
$edit['attributes[class]'] = 'testdata';
$edit['attributes[target]'] = LINK_TARGET_NEW_WINDOW;
$edit['attributes[rel]'] = 'nofollow';
$this->drupalPost('admin/content/node-type/'. $url_type .'/fields/'. $field['field_name'],
$edit, t('Save field settings'));
$this->assertText(t('Saved field @field_name', array('@field_name' => $field['field_name'])));
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$title = 'title_'. $this->randomName(20);
$edit[$field['field_name'] .'[0][title]'] = $title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertText($title, 'Make sure the link title/text shows');
//$this->assertRaw(' title="test_data"', "Do we show the title?");
$this->assertLinkOnNode($field['field_name'],
l($title,
'http://www.example.com/test',
array('attributes' => array('target' => '_blank',
'rel' => 'nofollow',
'class' => 'testdata'))));
//$this->pass($this->content);
}
function test_Link_With_Title_Attribute() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => 'test_title',
),
);
$field = $this->createField($field_settings, 0);
$field_db_info = content_database_info($field);
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertRaw(' title="test_title"', "Do we show the title?");
//$this->assertRaw(l('http://www.example.com/test', 'http://www.example.com/test', array('attributes' => array('title' => 'test_title'))));
}
function test_Link_With_Title_Attribute_form() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$field = $this->createField($field_settings, 0);
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
$edit = array('attributes[title]' => 'test_data');
$this->drupalPost('admin/content/node-type/'. $url_type .'/fields/'. $field['field_name'],
$edit, t('Save field settings'));
$this->assertText(t('Saved field @field_name', array('@field_name' => $field['field_name'])));
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$title = 'title_'. $this->randomName(20);
$edit[$field['field_name'] .'[0][title]'] = $title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertText($title, 'Make sure the link title/text shows');
$this->assertRaw(' title="test_data"', "Do we show the title?");
}
/**
* When the title attribute matches the link title, we need to suppress
* the title attribute.
*/
function test_Link_With_Title_Attribute_Not_Shown_form() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$common_title = 'title_'. $this->randomName(20);
$field = $this->createField($field_settings, 0);
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
$edit = array('attributes[title]' => $common_title);
$this->drupalPost('admin/content/node-type/'. $url_type .'/fields/'. $field['field_name'],
$edit, t('Save field settings'));
$this->assertText(t('Saved field @field_name', array('@field_name' => $field['field_name'])));
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$edit[$field['field_name'] .'[0][title]'] = $common_title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertRaw('>'. $common_title .'<', 'Make sure the link title/text shows');
$this->assertNoRaw(' title="'. $common_title .'"',
"Do we hide the title, since it matches the link title?");
//$this->pass($this->content);
}
/**
* When the title attribute matches the link title, we need to suppress
* the title attribute.
*/
function test_Link_without_title_attribute() {
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$common_title = 'title_'. $this->randomName(20);
$field = $this->createField($field_settings, 0);
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$edit[$field['field_name'] .'[0][title]'] = $common_title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertRaw('>'. $common_title .'<', 'Make sure the link title/text shows');
$this->assertNoRaw(' title=""',
"Do we hide the title, since it is empty?");
}
/**
* This test exercises the bugfix for http://drupal.org/node/628902.
* It's also making sure that if you set up a link field with 'rel="nofollow"'
* and point it internally, then the link does not show rel="nofollow".
*/
function test_rel_nofollow_bug() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$field_name = 'field_'. $name;
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name,
'attributes[rel]' => 'nofollow'), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'test', // internal link!
);
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
//$this->pass($this->content);
$this->assertRaw(l($name, 'test'));//, array('attributes' => array('rel' => ''))));
}
function test_rel_nofollow_on_external_link() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$field_name = 'field_'. $name;
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name,
'attributes[rel]' => 'nofollow'), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(), // internal link!
);
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
//$this->pass($this->content);
$this->assertRaw(l($name, $input['href'], array('attributes' => array('rel' => 'nofollow'))));
}
/**
* Here we test the fix to #626932, where an empty or bad attributes value on the link at the field
* level would cause the site to die in _link_sanitize, when the non-array $field['attributes'] is added
* to another array.
*/
function test_bad_attributes_bugfix_null_global_settings() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$field_name = 'field_'. $name;
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// ruin the stored data in content_node_field.
// Here we replace the entire $field with a blank. The structure of the table
// prevents it from being set to a null, sadly.
db_query("UPDATE {content_node_field} SET global_settings = '' WHERE field_name = '%s'",
$field_name);
// create page form
$this->drupalGet('node/add/page');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'test', // internal link!
);
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
//$this->pass($this->content);
$this->assertRaw(l($name, 'test'));//, array('attributes' => array('rel' => ''))));
}
/**
* Here we test the fix to #626932, where an empty or bad attributes value on the link at the field
* level would cause the site to die in _link_sanitize, when the non-array $field['attributes'] is added
* to another array.
*/
function test_bad_attributes_bugfix_string_attributes() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$field_name = 'field_'. $name;
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// ruin the stored data in content_node_field.
// Here we set $field['attributes'] equal to a string of length 0.
db_query("UPDATE {content_node_field} SET global_settings = '%s' WHERE field_name = '%s'",
'a:6:{s:10:"attributes";s:0:"";s:7:"display";a:1:{s:10:"url_cutoff";s:2:"80";}s:3:"url";i:0;s:5:"title";s:8:"optional";s:11:"title_value";s:0:"";s:13:"enable_tokens";i:1;}', $field_name);
// create page form
$this->drupalGet('node/add/page');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'test', // internal link!
);
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
//$this->pass($this->content);
$this->assertRaw(l($name, 'test'));//, array('attributes' => array('rel' => ''))));
}
/**
* A simple test that just creates a new node type, adds a link field to it, creates a new node of that type, and makes sure
* that the node is being displayed.
*/
function testOptionalUrlStaticTitleDisplays() {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$title_value = $this->randomName();
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error.
'url' => FALSE,
'title' => 'value',
'title_value' => $title_value,
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$node->promote = 1; // We want this to show on front page for the teaser test.
$node->{$field['field_name']}[0] = $this->createLink('', '');
node_save($node);
// Does this display on the node page?
$this->drupalGet('node/'. $this->nodes[0]->nid);
//$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com'));
$this->assertNoRaw($title_value, 'Title value should not be displayed for a blank field if the title is static.');
// Does this display on the front page?
$this->drupalGet('<front>');
// reset the zebra!
$this->zebra = 0;
//$this->assertLinkOnNode($field['field_name'], l('Test Link', 'http://www.example.com'));
$this->assertNoRaw($title_value, 'Title value should not be displayed for a blank field if the title is static.');
}
}

View file

@ -0,0 +1,48 @@
<?php
/**
* @file
* Basic CRUD simpletests for the link module, based off of content.crud.test in CCK.
*/
// Need to include content.crud.test so we can inherit from it's ContentCrudTestCase.
require_once(drupal_get_path('module', 'content') .'/tests/content.crud.test');
class LinkContentCrudTest extends ContentCrudTestCase {
function getInfo() {
return array(
'name' => t('Link CRUD - Basic API tests'),
'description' => t('Tests the field CRUD (create, read, update, delete) API. <strong>Requires <a href="@schema_link">Schema module</a>.</strong>', array('@schema_link' => 'http://www.drupal.org/project/schema')),
'group' => t('Link'),
);
}
function setUp() {
parent::setUp('link');
$this->loginWithPermissions();
}
/**
* All we're doing here is creating a content type, creating a simple link field
* on that content type, and making sure said field exists in the database.
*/
function testLinkCreateFieldAPI() {
$this->acquireContentTypes(1);
$field = $this->createField(array('type' => 'link', 'widget_type' => 'link'), 0);
//$this->pass(print_r($this->content_types, TRUE));
//$this->pass(print_r($field, TRUE));
$table_schema = drupal_get_schema();
//$this->pass(print_r(array_keys($table_schema), TRUE));
// Check the schema - the values should be in the per-type table.
$this->assertSchemaMatchesTables(array(
'per_type' => array(
$this->content_types[0]->type => array($field['field_name'] => array('url', 'title', 'attributes')),
),
));
}
}

View file

@ -0,0 +1,340 @@
<?php
/**
* @file
* Testing CRUD API in the browser.
*/
/**
* Testing that users can not input bad URLs or labels
*/
class LinkUITest extends DrupalWebTestcase {
/**
* Link supposed to be good
*/
const LINK_INPUT_TYPE_GOOD = 0;
/**
* Link supposed to have a bad title
*/
const LINK_INPUT_TYPE_BAD_TITLE = 1;
/**
* Link supposed to have a bad URL
*/
const LINK_INPUT_TYPE_BAD_URL = 2;
/**
* Implementation of getInfo().
*/
function getInfo() {
return array(
'name' => t('Link CRUD - browser test'),
'description' => t('Tests the field CRUD (create, read, update, delete) API.'),
'group' => t('Link'),
);
}
/**
* Implementation of setUp().
*/
function setUp() {
parent::setUp('content', 'link');
}
/**
* Creates a link field for the "page" type and creates a page with a link.
*/
function testLinkCreate() {
//libxml_use_internal_errors(true);
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array('validate_url' => TRUE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input_test_cases = array(
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
'msg' => 'Link found',
'type' => self::LINK_INPUT_TYPE_GOOD
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '<script>alert("hi");</script>',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '<script src="http://devil.site.com"></script>',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '" onmouseover="alert(\'hi\')',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '\' onmouseover="alert(\'hi\')',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'javascript:alert("http://example.com/' . $this->randomName() . '")',
'label' => $this->randomName(),
'msg' => 'js url',
'type' => self::LINK_INPUT_TYPE_BAD_URL
),
);
foreach ($input_test_cases as $input) {
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'],
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
if ($input['type'] == self::LINK_INPUT_TYPE_BAD_URL) {
$this->assertRaw(t('Not a valid URL.'), 'Not a valid URL: ' . $input['href']);
continue;
}
else {
$this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), 'Page created: ' . $input['href']);
}
$url = $this->getUrl();
// change to anonym user
$this->drupalLogout();
$this->drupalGet($url);
//debug($this);
// If simpletest starts using something to override the error system, this will flag
// us and let us know it's broken.
$this->assertFalse(libxml_use_internal_errors(TRUE));
$path = '//a[@href="'. $input['href'] .'" and text()="'. $input['label'] .'"]';
//$this->pass(htmlentities($path));
$elements = $this->xpath($path);
libxml_use_internal_errors(FALSE);
$this->assertIdentical(isset($elements[0]), $input['type'] == self::LINK_INPUT_TYPE_GOOD, $input['msg']);
}
//libxml_use_internal_errors(FALSE);
}
/**
* Creates a link field for the "page" type and creates a page with a link.
* Just like the above test, only here we're turning off the validation on the field.
*/
function testLinkCreate_NoValidation() {
//libxml_use_internal_errors(true);
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array('validate_url' => FALSE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
_content_type_info(TRUE);
$fields = content_fields();
$this->assertTRUE(0 === $fields['field_'. $name]['validate_url'], 'Make sure validation is off.');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input_test_cases = array(
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
'msg' => 'Link found',
'type' => self::LINK_INPUT_TYPE_GOOD
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '<script>alert("hi");</script>',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '<script src="http://devil.site.com"></script>',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '" onmouseover="alert(\'hi\')',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName() . '\' onmouseover="alert(\'hi\')',
'msg' => 'js label',
'type' => self::LINK_INPUT_TYPE_BAD_TITLE
),
array(
'href' => 'javascript:alert("http://example.com/' . $this->randomName() . '")',
'label' => $this->randomName(),
'msg' => 'js url',
'type' => self::LINK_INPUT_TYPE_BAD_URL
),
);
foreach ($input_test_cases as $input) {
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'],
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
if ($input['type'] == self::LINK_INPUT_TYPE_BAD_URL) {
//$this->assertRaw(t('Not a valid URL.'), 'Not a valid URL: ' . $input['href']);
$this->assertNoRaw($input['href']);
$this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), 'Page created: ' . $input['href']);
continue;
}
else {
$this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), 'Page created: ' . $input['href']);
}
$url = $this->getUrl();
// change to anonym user
$this->drupalLogout();
$this->drupalGet($url);
//debug($this);
// If simpletest starts using something to override the error system, this will flag
// us and let us know it's broken.
$this->assertFalse(libxml_use_internal_errors(TRUE));
$path = '//a[@href="'. $input['href'] .'" and text()="'. $input['label'] .'"]';
//$this->pass(htmlentities($path));
$elements = $this->xpath($path);
libxml_use_internal_errors(FALSE);
$this->assertIdentical(isset($elements[0]), $input['type'] == self::LINK_INPUT_TYPE_GOOD, $input['msg']);
}
//libxml_use_internal_errors(FALSE);
}
/**
* Testing that if you use <strong> in a static title for your link, that the
* title actually displays <strong>.
*/
function testStaticLinkCreate() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$field_name = 'field_'. $name;
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => '<strong>'. $name .'</strong>'), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName()
);
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l('<strong>'. $name .'</strong>', $input['href'], array('html' => TRUE)));
}
/**
* If we're creating a new field and just hit 'save' on the default options, we want to make
* sure they are set to the expected results.
*/
function testCRUDCreateFieldDefaults() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
_content_type_info(TRUE);
$fields = content_fields();
$field = $fields['field_'. $name];
$this->assertTrue(1 === $field['validate_url'], 'Make sure validation is on.');
$this->assertFalse($field['required'], 'Make sure field is not required.');
$this->assertEqual($field['title'], 'optional', 'Title should be optional by default.');
$this->assertFalse($field['enable_tokens'], 'Enable Tokens should be off by default.');
$this->assertEqual($field['display']['url_cutoff'], 80, 'Url cutoff should be at 80 characters.');
$this->assertEqual($field['attributes']['target'], 'default', 'Target should be "default"');
$this->assertFalse($field['attributes']['rel'], 'Rel should be blank by default.');
$this->assertFalse($field['attributes']['class'], 'By default, no class should be set.');
$this->assertFalse($field['attributes']['title'], 'By default, no title should be set.');
//$this->fail('<pre>'. print_r($fields['field_'. $name], TRUE) .'</pre>');
}
}

View file

@ -0,0 +1,531 @@
<?php
/**
* @file
* Contains simpletests making sure token integration works.
*/
/**
* Testing that tokens can be used in link titles
*/
class LinkTokenTest extends ContentCrudTestCase {
public $permissions = array(
'access content',
'administer content types',
'administer nodes',
'administer filters',
'access comments',
'post comments',
'post comments without approval',
'access administration pages',
);
/**
* Implementation of getInfo().
*/
function getInfo() {
return array(
'name' => t('Link tokens - browser test'),
'description' => t('Tests including tokens in link titles, making sure they appear in node views. <strong>Requires <a href="@token_link">Token module</a>.</strong>'),
'group' => t('Link'),
);
}
/**
* Implementation of setUp().
*/
function setUp() {
parent::setUp('content', 'link', 'token');
}
/**
* Creates a link field with a required title enabled for user-entered tokens.
* Creates a node with a token in the link title and checks the value.
*/
function testUserTokenLinkCreate() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'required',
'enable_tokens' => TRUE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'] . " [type]",
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($input['label'] . ' page', $input['href']));
}
/**
* Creates a link field with a static title and an admin-entered token.
* Creates a node with a link and checks the title value.
*/
function testStaticTokenLinkCreate() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name . ' [type]',
'enable_tokens' => FALSE,
), t('Save field settings'));
// Is filed created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName()
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($name . ' page', $input['href']));
}
/**
* Creates a link field with a static title and an admin-entered token.
* Creates a node with a link and checks the title value.
*
* Basically, I want to make sure the [title-raw] token works, because it's a
* token that changes from node to node, where [type]'s always going to be the
* same.
*/
function testStaticTokenLinkCreate2() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'value',
'title_value' => $name . ' [title-raw]',
'enable_tokens' => FALSE,
), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName()
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $name,
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($name .' '. $name, $input['href']));
}
function test_Link_With_Title_Attribute_token_url_form() {
$this->loginWithPermissions($this->permissions);
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$field = $this->createField($field_settings, 0);
//$this->fail('<pre>'. print_r($field, TRUE) .'</pre>');
$field_name = $field['field_name'];
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
$edit = array('attributes[title]' => '['. $field_name .'-url]',
'enable_tokens' => FALSE);
$this->drupalPost('admin/content/node-type/'. $url_type .'/fields/'. $field['field_name'],
$edit, t('Save field settings'));
$this->assertText(t('Saved field @field_name', array('@field_name' => $field['field_name'])));
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$test_link_url = 'http://www.example.com/test';
$edit[$field['field_name'] .'[0][url]'] = $test_link_url;
$title = 'title_'. $this->randomName(20);
$edit[$field['field_name'] .'[0][title]'] = $title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertText($title, 'Make sure the link title/text shows');
$this->assertRaw(' title="'. $test_link_url .'"', "Do we show the link url as the title attribute?");
$this->assertNoRaw(' title="['. $field_name .'-url]"');
$this->assertTrue(module_exists('token'), t('Assure that Token Module is enabled.'));
//$this->fail($this->content);
}
/**
* If the title of the link is set to the title attribute, then the title
* attribute isn't supposed to show.
*/
function test_Link_With_Title_Attribute_token_title_form() {
$this->loginWithPermissions($this->permissions);
$this->acquireContentTypes(1);
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(
'class' => '',
'target' => 'default',
'rel' => 'nofollow',
'title' => '',
),
);
$field = $this->createField($field_settings, 0);
$field_name = $field['field_name'];
$field_db_info = content_database_info($field);
$url_type = str_replace('_', '-', $this->content_types[0]->type);
$edit = array('attributes[title]' => '['. $field_name .'-title]',
'enable_tokens' => FALSE);
$this->drupalPost('admin/content/node-type/'. $url_type .'/fields/'. $field['field_name'],
$edit, t('Save field settings'));
$this->assertText(t('Saved field @field_name', array('@field_name' => $field['field_name'])));
// So, having saved this field_name, let's see if it works...
$this->acquireNodes(1);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'http://www.example.com/test';
$title = 'title_'. $this->randomName(20);
$edit[$field['field_name'] .'[0][title]'] = $title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)));
$this->drupalGet('node/'. $node->nid);
$this->assertText($title, 'Make sure the link title/text shows');
$this->assertNoRaw(' title="'. $title .'"', "We should not show the link title as the title attribute?");
$this->assertNoRaw(' title="['. $field_name .'-title]"');
//$this->fail($this->content);
}
/**
* Trying to set the url to contain a token.
*/
function testUserTokenLinkCreateInURL() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'required',
'enable_tokens' => TRUE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'],
$field_name . '[0][url]' => $input['href'] . "/[type]",
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($input['label'], $input['href'] .'/page'));
//$this->fail($this->content);
}
/**
* If 'enable_tokens' is off, then the url shouldn't be filtered through the token module.
*/
function testUserTokenLinkCreateInURLFail() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'required',
'enable_tokens' => FALSE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'],
$field_name . '[0][url]' => $input['href'] . "/[type]",
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($input['label'], $input['href'] .'/[type]'));
//$this->fail($this->content);
}
/**
* Trying to set the url to contain a token.
*/
function testUserTokenLinkCreateInURL2() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'required',
'enable_tokens' => TRUE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'],
$field_name . '[0][url]' => $input['href'] . "/[author-uid]",
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($input['label'], $input['href'] .'/'. $account->uid));
}
/**
* Creates a link field with a required title enabled for user-entered tokens.
* Creates a node with a token in the link title and checks the value.
*/
function testHostTokenLinkCreate() {
$account = $this->drupalCreateUser(array('administer content types', 'access content', 'create page content'));
$this->drupalLogin($account);
// create field
$name = strtolower($this->randomName());
$edit = array(
'_add_new_field[label]' => $name,
'_add_new_field[field_name]' => $name,
'_add_new_field[type]' => 'link',
'_add_new_field[widget_type]' => 'link',
);
$this->drupalPost('admin/content/node-type/page/fields', $edit, t('Save'));
$this->drupalPost(NULL, array(
'title' => 'required',
'enable_tokens' => TRUE), t('Save field settings'));
// Is field created?
$this->assertRaw(t('Added field %label.', array('%label' => $name)), 'Field added');
// create page form
$this->drupalGet('node/add/page');
$field_name = 'field_' . $name;
$this->assertField($field_name . '[0][title]', 'Title found');
$this->assertField($field_name . '[0][url]', 'URL found');
$input = array(
'href' => 'http://example.com/' . $this->randomName(),
'label' => $this->randomName(),
);
$this->drupalLogin($account);
$this->drupalGet('node/add/page');
$edit = array(
'title' => $input['label'],
$field_name . '[0][title]' => $input['label'] . " [$field_name-host]",
$field_name . '[0][url]' => $input['href'],
);
$this->drupalPost(NULL, $edit, t('Save'));
$url = $this->getUrl();
// change to anonymous user
$this->drupalLogout();
$this->drupalGet($url);
$this->assertRaw(l($input['label'] . ' example.com', $input['href']));
}
}

View file

@ -0,0 +1,497 @@
<?php
/**
* @file
* Tests that exercise the validation functions in the link module.
*/
// Let's include the parent class.
module_load_include('test', 'content', 'tests/content.crud');
class LinkValidateTestCase extends ContentCrudTestCase {
public $permissions = array(
'access content',
'administer content types',
'administer nodes',
'administer filters',
'access comments',
'post comments',
'post comments without approval',
'access administration pages',
);
function setUp() {
parent::setUp('link');
$this->loginWithPermissions($this->permissions);
}
function createLink($url, $title, $attributes = array()) {
return array(
'url' => $url,
'title' => $title,
'attributes' => $attributes,
);
}
/**
* Takes a url, and sees if it can validate that the url is valid.
*/
function link_test_validate_url($url) {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error.
'validate_url' => 1,
);
$field = $this->createField($field_settings, 0);
//$this->fail('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(1);
//$this->fail("We now have ". count($this->nodes) ." nodes.");
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = $url;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertText(t('@type @title has been updated.',
array('@title' => $node->title,
'@type' => $this->content_types[0]->name)),
t('Testing %url', array('%url' => $url)));
$this->assertEqual($url, $node->{$field['field_name']}[0]['url']);
}
}
class LinkValidateTest extends LinkValidateTestCase {
function getInfo() {
return array(
'name' => t('Link Validation Tests'),
'description' => t('Tests the field validation.'),
'group' => t('Link'),
);
}
function test_link_validate_basic_url() {
$this->link_test_validate_url('http://www.example.com');
}
/**
* Test if we're stopped from posting a bad url on default validation.
*/
function test_link_validate_bad_url_validate_default() {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error
//'validate_url' => 1,
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'edik:naw';
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
//$this->pass($this->content);
$this->assertText(t('Not a valid URL.'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertNotEqual('edik:naw', $node->{$field['field_name']}[0]['url']);
}
/**
* Test if we're stopped from posting a bad url with validation on.
*/
function test_link_validate_bad_url_validate_on() {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error
'validate_url' => 1,
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'edik:naw';
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
//$this->pass($this->content);
$this->assertText(t('Not a valid URL.'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertNotEqual('edik:naw', $node->{$field['field_name']}[0]['url']);
}
/**
* Test if we can post a bad url if the validation is expressly turned off.
*/
function test_link_validate_bad_url_validate_off() {
$this->acquireContentTypes(1);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error
'validate_url' => 0,
);
$field = $this->createField($field_settings, 0);
//$this->pass('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$edit[$field['field_name'] .'[0][url]'] = 'edik:naw';
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
//$this->pass($this->content);
$this->assertNoText(t('Not a valid URL.'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertEqual('edik:naw', $node->{$field['field_name']}[0]['url']);
}
/**
* Test if a bad url can sneak through un-filtered if we play with the validation...
*/
function test_link_validate_switching_between_validation_status() {
$this->acquireContentTypes(1);
$account = $this->drupalCreateUser(array('administer content types',
'administer nodes',
'access administration pages',
'access content',
'create '. $this->content_types[0]->type .' content',
'edit any '. $this->content_types[0]->type .' content'));
$this->drupalLogin($account);
variable_set('node_options_'. $this->content_types[0]->name, array('status', 'promote'));
$field_settings = array(
'type' => 'link',
'widget_type' => 'link',
'type_name' => $this->content_types[0]->name,
'attributes' => array(), // <-- This is needed or we have an error
'validate_url' => 0,
);
$field = $this->createField($field_settings, 0);
//$this->fail('<pre>'. print_r($field, TRUE) .'</pre>');
$field_db_info = content_database_info($field);
$this->acquireNodes(2);
$node = node_load($this->nodes[0]->nid);
$this->drupalGet('node/'. $this->nodes[0]->nid);
$edit = array();
$title = $this->randomName();
$url = 'javascript:alert("http://example.com/' . $this->randomName() . '")';
$edit[$field['field_name'] .'[0][url]'] = $url;
$edit[$field['field_name'] .'[0][title]'] = $title;
$this->drupalPost('node/'. $this->nodes[0]->nid .'/edit', $edit, t('Save'));
//$this->pass($this->content);
$this->assertNoText(t('Not a valid URL.'));
// Make sure we get a new version!
$node = node_load($this->nodes[0]->nid, NULL, TRUE);
$this->assertEqual($url, $node->{$field['field_name']}[0]['url']);
$this->drupalGet('node/'. $node->nid);
$this->assertNoRaw($url, 'Make sure Javascript does not display.');
// Turn the array validation back _on_.
$edit = array('validate_url' => TRUE);
$node_type_link = str_replace('_', '-', $node->type);
//$this->drupalGet('admin/content/node-type/'. $node_type_link .'/fields'); ///'. $field['field_name']);
//$this->fail($this->content);
$this->drupalPost('admin/content/node-type/'. $node_type_link .'/fields/'. $field['field_name'], $edit, t('Save field settings'));
$this->drupalGet('node/'. $node->nid);
// This actually works because the display_url goes through the core
// url() function. But we should have a test that makes sure it continues
// to work.
$this->assertNoRaw($url, 'Make sure Javascript does not display.');
//$this->fail($this->content);
}
// Validate that '<front>' is a valid url.
function test_link_front_url() {
$this->link_test_validate_url('<front>');
}
// Validate that an internal url would be accepted.
function test_link_internal_url() {
$this->link_test_validate_url('node/32');
}
// Validate a simple mailto.
function test_link_mailto() {
$this->link_test_validate_url('mailto:jcfiala@gmail.com');
}
function test_link_external_https() {
$this->link_test_validate_url('https://www.example.com/');
}
function test_link_ftp() {
$this->link_test_validate_url('ftp://www.example.com/');
}
}
class LinkValidateTestNews extends LinkValidateTestCase {
function getInfo() {
return array(
'name' => t('Link News Validation Tests'),
'description' => t('Tests the field validation for usenet urls.'),
'group' => t('Link'),
);
}
// Validate a news link to a message group
function test_link_news() {
$this->link_test_validate_url('news:comp.infosystems.www.misc');
}
// Validate a news link to a message id. Said ID copied off of google groups.
function test_link_news_message() {
$this->link_test_validate_url('news:hj0db8$vrm$1@news.eternal-september.org');
}
}
class LinkValidateSpecificURL extends LinkValidateTestCase {
function getInfo() {
return array(
'name' => t('Link Specific URL Validation Tests'),
'description' => t('Tests field validation with unusual urls'),
'group' => t('Link'),
);
}
// Lets throw in a lot of umlouts for testing!
function test_umlout_url() {
$this->link_test_validate_url('http://üÜü.exämple.com/nöde');
}
function test_umlout_mailto() {
$this->link_test_validate_url('mailto:Üser@exÅmple.com');
}
function test_german_b_url() {
$this->link_test_validate_url('http://www.test.com/ßstuff');
}
function test_special_n_url() {
$this->link_test_validate_url('http://www.testÑñ.com/');
}
function test_curly_brackets_in_query() {
$this->link_test_validate_url('http://www.healthyteennetwork.org/index.asp?Type=B_PR&SEC={2AE1D600-4FC6-4B4D-8822-F1D5F072ED7B}&DE={235FD1E7-208D-4363-9854-4E6775EB8A4C}');
}
/**
* Here, we're testing that a very long url is stored properly in the db.
*
* Basicly, trying to test http://drupal.org/node/376818
*/
function testLinkURLFieldIsBig() {
$long_url = 'http://th.wikipedia.org/wiki/%E0%B9%82%E0%B8%A3%E0%B8%87%E0%B9%80%E0%B8%A3%E0%B8%B5%E0%B8%A2%E0%B8%99%E0%B9%80%E0%B8%9A%E0%B8%8D%E0%B8%88%E0%B8%A1%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B8%B9%E0%B8%97%E0%B8%B4%E0%B8%A8_%E0%B8%99%E0%B8%84%E0%B8%A3%E0%B8%A8%E0%B8%A3%E0%B8%B5%E0%B8%98%E0%B8%A3%E0%B8%A3%E0%B8%A1%E0%B8%A3%E0%B8%B2%E0%B8%8A';
$this->link_test_validate_url($long_url);
}
}
/**
* A series of tests of links, only going against the link_validate_url function in link.module.
*
* Validation is guided by the rules in http://tools.ietf.org/html/rfc1738 !
*/
class LinkValidateUrlLight extends DrupalUnitTestCase {
function setUp() {
// do we need to include something here?
module_load_include('module', 'link');
module_load_include('inc', 'link');
}
function getInfo() {
return array(
'name' => t('Link Light Validation Tests'),
'description' => t('Tests the link_validate_url() function by itself, without invoking the full drupal/cck lifecycle.'),
'group' => t('Link'),
);
}
/**
* Translates the LINK type constants to english for display and debugging of tests
*/
function name_Link_Type($type) {
switch ($type) {
case LINK_FRONT:
return "Front";
case LINK_EMAIL:
return "Email";
case LINK_NEWS:
return "Newsgroup";
case LINK_INTERNAL:
return "Internal Link";
case LINK_EXTERNAL:
return "External Link";
case FALSE:
return "Invalid Link";
default:
return "Bad Value:". $type;
}
}
// Make sure that a link labelled <front> works.
function testValidateFrontLink() {
$valid = link_validate_url('<front>');
$this->assertEqual(LINK_FRONT, $valid, 'Make sure that front link is verfied and identified');
}
function testValidateEmailLink() {
$valid = link_validate_url('mailto:bob@example.com');
$this->assertEqual(LINK_EMAIL, $valid, "Make sure a basic mailto is verified and identified");
}
function testValidateEmailLinkBad() {
$valid = link_validate_url(':bob@example.com');
$this->assertEqual(FALSE, $valid, 'Make sure just a bad address is correctly failed');
}
function testValidateNewsgroupLink() {
$valid = link_validate_url('news:comp.infosystems.www.misc');
$this->assertEqual(LINK_NEWS, $valid, 'Make sure link to newsgroup validates as news.');
}
function testValidateNewsArticleLink() {
$valid = link_validate_url('news:hj0db8$vrm$1@news.eternal-september.org');
$this->assertEqual(LINK_NEWS, $valid, 'Make sure link to specific article valiates as news.');
}
function testValidateBadNewsgroupLink() {
$valid = link_validate_url('news:comp.bad_name.misc');
$this->assertEqual(FALSE, $valid, 'newsgroup names can\'t contain underscores, so it should come back as invalid.');
}
function testValidateInternalLink() {
$valid = link_validate_url('node/5');
$this->assertEqual(LINK_INTERNAL, $valid, 'Test normal internal link.');
}
function testValidateInternalLinkWithDot() {
$valid = link_validate_url('rss.xml');
$this->assertEqual(LINK_INTERNAL, $valid, 'Test rss.xml internal link.');
}
function testValidateInternalLinkToFile() {
$valid = link_validate_url('files/test.jpg');
$this->assertEqual(LINK_INTERNAL, $valid, 'Test files/test.jpg internal link.');
}
function testValidateExternalLinks() {
$links = array(
'http://localhost:8080/',
'www.example.com',
'www.example.com/',
'http://username:p%40ssw0rd!@www.example.com/',
'http://@www.example.com/',
'http://username:@www.example.com/',
'http://username:password@www.example.com:8080/',
'http://127.0.0.1:80/',
'http://127.173.24.255:4723/',
'127.173.24.255:4723/',
'http://255.255.255.255:4823/',
'www.test-site.com',
'http://example.com/index.php?q=node/123',
'http://example.com/index.php?page=this\that',
'http://example.com/?first_name=Joe Bob&last_name=Smith',
// Anchors
'http://www.example.com/index.php#test',
'http://www.example.com/index.php#this@that.',
'http://www.example.com/index.php#',
'http://www.cnn.com/video/#/video/politics/2008/12/09/intv.madeleine.albright.cnn',
'http://www.archive.org/stream/aesopsfables00aesorich#page/n7/mode/2up',
'http://www.example.com/blah/#this@that?',
);
// Test all of the protocols.
$allowed_protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'));
foreach ($allowed_protocols as $protocol) {
if ($protocol !== 'news' && $protocol !== 'mailto') {
$links[] = $protocol .'://www.example.com';
}
}
foreach ($links as $link) {
$valid = link_validate_url($link);
$this->assertEqual(LINK_EXTERNAL, $valid, 'Testing that '. $link .' is a valid external link.');
}
}
function testInvalidExternalLinks() {
$links = array(
'http://www.ex ample.com/',
'//www.example.com/',
'http://25.0.0/', // bad ip!
'http://4827.0.0.2/',
'http://www.testß.com/', // ß not allowed in domain names!
//'http://www.-fudge.com/', // domains can't have sections starting with a dash.
);
foreach ($links as $link) {
$valid = link_validate_url($link);
$this->assertEqual(FALSE, $valid, 'Testing that '. $link .' is not a valid link.');
}
}
}

View file

@ -0,0 +1,109 @@
<?php
/**
* @file
* Contains functions handling views integration.
*/
/**
* Implementation of hook_views_handlers().
*/
function link_views_handlers() {
return array(
'info' => array(
'path' => drupal_get_path('module', 'link') .'/views',
),
'handlers' => array(
'link_views_handler_argument_target' => array(
'parent' => 'views_handler_argument',
),
'link_views_handler_filter_protocol' => array(
'parent' => 'views_handler_filter_string',
),
),
);
}
/**
* Return CCK Views data for the link_field_settings($op == 'views data').
*/
function link_views_content_field_data($field) {
// Build the automatic views data provided for us by CCK.
// This creates all the information necessary for the "url" field.
$data = content_views_field_views_data($field);
$db_info = content_database_info($field);
$table_alias = content_views_tablename($field);
$field_types = _content_field_types();
// Tweak the automatic views data for the link "url" field.
// Set the filter title to "@label URL"
$data[$table_alias][$field['field_name'] .'_url']['filter']['title'] = t('@label URL', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']);
// Remove the argument handling for URLs.
unset($data[$table_alias][$field['field_name'] .'_url']['argument']);
// Build out additional views data for the link "title" field.
$data[$table_alias][$field['field_name'] .'_title'] = array(
'group' => t('Content'),
'title' => t('@label title', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']) .' ('. $field['field_name'] .')',
'help' => $data[$table_alias][$field['field_name'] .'_url']['help'],
'argument' => array(
'field' => $db_info['columns']['title']['column'],
'tablename' => $db_info['table'],
'handler' => 'content_handler_argument_string',
'click sortable' => TRUE,
'name field' => '', // TODO, mimic content.views.inc :)
'content_field_name' => $field['field_name'],
'allow_empty' => TRUE,
),
'filter' => array(
'field' => $db_info['columns']['title']['column'],
'title' => t('@label title', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']),
'tablename' => $db_info['table'],
'handler' => 'content_handler_filter_string',
'additional fields' => array(),
'content_field_name' => $field['field_name'],
'allow_empty' => TRUE,
),
'sort' => array(
'field' => $db_info['columns']['title']['column'],
'tablename' => $db_info['table'],
'handler' => 'content_handler_sort',
'content_field_name' => $field['field_name'],
'allow_empty' => TRUE,
),
);
// Build out additional Views filter for the link "protocol" pseudo field.
$data[$table_alias][$field['field_name'] .'_protocol'] = array(
'group' => t('Content'),
'title' => t('@label protocol', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']) .' ('. $field['field_name'] .')',
'help' => $data[$table_alias][$field['field_name'] .'_url']['help'],
'filter' => array(
'field' => $db_info['columns']['url']['column'],
'title' => t('@label protocol', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']),
'tablename' => $db_info['table'],
'handler' => 'link_views_handler_filter_protocol',
'additional fields' => array(),
'content_field_name' => $field['field_name'],
'allow_empty' => TRUE,
),
);
// Build out additional Views argument for the link "target" pseudo field.
$data[$table_alias][$field['field_name'] .'_target'] = array(
'group' => t('Content'),
'title' => t('@label target', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']) .' ('. $field['field_name'] .')',
'help' => $data[$table_alias][$field['field_name'] .'_url']['help'],
'argument' => array(
'field' => $db_info['columns']['attributes']['column'],
'title' => t('@label target', array('@label' => t($field_types[$field['type']]['label']))) .': '. t($field['widget']['label']) .' ('. $field['field_name'] .')',
'tablename' => $db_info['table'],
'handler' => 'link_views_handler_argument_target',
'additional fields' => array(),
'content_field_name' => $field['field_name'],
'allow_empty' => TRUE,
),
);
return $data;
}

View file

@ -0,0 +1,142 @@
<?php
/**
* @file
* Argument handler to filter results by target.
*/
/**
* Argument handler to filter results by target.
*/
class link_views_handler_argument_target extends views_handler_argument {
/**
* Provide a default options form for the argument.
*/
function options_form(&$form, &$form_state) {
$defaults = $this->default_actions();
$form['title'] = array(
'#prefix' => '<div class="clear-block">',
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Title'),
'#default_value' => $this->options['title'],
'#description' => t('The title to use when this argument is present; it will override the title of the view and titles from previous arguments. You can use percent substitution here to replace with argument titles. Use "%1" for the first argument, "%2" for the second, etc.'),
);
$form['clear_start'] = array(
'#value' => '<div class="clear-block">',
);
$form['defaults_start'] = array(
'#value' => '<div class="views-left-50">',
);
$form['default_action'] = array(
'#type' => 'radios',
'#title' => t('Action to take if argument is not present'),
'#default_value' => $this->options['default_action'],
);
$form['defaults_stop'] = array(
'#value' => '</div>',
);
$form['wildcard'] = array(
'#prefix' => '<div class="views-right-50">',
// prefix and no suffix means these two items will be grouped together.
'#type' => 'textfield',
'#title' => t('Wildcard'),
'#size' => 20,
'#default_value' => $this->options['wildcard'],
'#description' => t('If this value is received as an argument, the argument will be ignored; i.e, "all values"'),
);
$form['wildcard_substitution'] = array(
'#suffix' => '</div>',
'#type' => 'textfield',
'#title' => t('Wildcard title'),
'#size' => 20,
'#default_value' => $this->options['wildcard_substitution'],
'#description' => t('The title to use for the wildcard in substitutions elsewhere.'),
);
$form['clear_stop'] = array(
'#value' => '</div>',
);
$options = array();
$validate_options = array();
foreach ($defaults as $id => $info) {
$options[$id] = $info['title'];
if (empty($info['default only'])) {
$validate_options[$id] = $info['title'];
}
if (!empty($info['form method'])) {
$this->{$info['form method']}($form, $form_state);
}
}
$form['default_action']['#options'] = $options;
$form['validate_type'] = array(
'#type' => 'select',
'#title' => t('Validator'),
'#default_value' => $this->options['validate_type'],
);
$validate_types = array('none' => t('<Basic validation>'));
$plugins = views_fetch_plugin_data('argument validator');
foreach ($plugins as $id => $info) {
$valid = TRUE;
if (!empty($info['type'])) {
$valid = FALSE;
if (empty($this->definition['validate type'])) {
continue;
}
foreach ((array) $info['type'] as $type) {
if ($type == $this->definition['validate type']) {
$valid = TRUE;
break;
}
}
}
// If we decide this validator is ok, add it to the list.
if ($valid) {
$plugin = views_get_plugin('argument validator', $id);
if ($plugin) {
$plugin->init($this->view, $this, $id);
if ($plugin->access()) {
$plugin->validate_form($form, $form_state, $id);
$validate_types[$id] = $info['title'];
}
}
}
}
asort($validate_types);
$form['validate_type']['#options'] = $validate_types;
// Show this gadget if *anything* but 'none' is selected
$form['validate_fail'] = array(
'#type' => 'select',
'#title' => t('Action to take if argument does not validate'),
'#default_value' => $this->options['validate_fail'],
'#options' => $validate_options,
);
}
/**
* Set up the query for this argument.
*
* The argument sent may be found at $this->argument.
*/
function query() {
$this->ensure_my_table();
// Because attributes are stored serialized, our only option is to also
// serialize the data we're searching for and use LIKE to find similar data.
$this->query->add_where(0, $this->table_alias .'.'. $this->real_field ." LIKE '%%%s%'", serialize(array('target' => $this->argument)));
}
}

View file

@ -0,0 +1,133 @@
<?php
/**
* @file
* Contains filter handlers for protocol filters with views.
*/
/**
* Filter handler for limiting a view to URLs of a certain protocol.
*/
class link_views_handler_filter_protocol extends views_handler_filter_string {
/**
* Set defaults for the filter options.
*/
function option_definition() {
$options = parent::option_definition();
$options['operator'] = array('default' => 'OR');
$options['value'] = array('default' => 'http');
$options['case'] = array('default' => 0);
return $options;
}
/**
* Define the operators supported for protocols.
*/
function operators() {
$operators = array(
'OR' => array(
'title' => t('Is one of'),
'short' => t('='),
'method' => 'op_protocol',
'values' => 1,
),
);
return $operators;
}
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$form['case'] = array(
'#type' => 'value',
'#value' => 0,
);
}
/**
* Provide a select list to choose the desired protocols.
*/
function value_form(&$form, &$form_state) {
// We have to make some choices when creating this as an exposed
// filter form. For example, if the operator is locked and thus
// not rendered, we can't render dependencies; instead we only
// render the form items we need.
$which = 'all';
if (!empty($form_state['exposed']) && empty($this->options['expose']['operator'])) {
$which = in_array($this->operator, $this->operator_values(1)) ? 'value' : 'none';
}
if ($which == 'all' || $which == 'value') {
$form['value'] = array(
'#type' => 'select',
'#title' => t('Protocol'),
'#default_value' => $this->value,
'#options' => drupal_map_assoc(variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal'))),
'#multiple' => 1,
'#size' => 4,
'#description' => t('The protocols displayed here are those globally available. You may add more protocols by modifying the <em>filter_allowed_protocols</em> variable in your installation.'),
);
}
}
/**
* Filter down the query to include only the selected protocols.
*/
function op_protocol($field, $upper) {
global $db_type;
$protocols = $this->value;
$where_conditions = array();
foreach ($protocols as $protocol) {
// Simple case, the URL begins with the specified protocol.
$condition = $field .' LIKE \''. $protocol .'%\'';
// More complex case, no protocol specified but is automatically cleaned up
// by link_cleanup_url(). RegEx is required for this search operation.
if ($protocol == 'http') {
if ($db_type == 'pgsql') {
// PostGreSQL code has NOT been tested. Please report any problems to the link issue queue.
// pgSQL requires all slashes to be double escaped in regular expressions.
// See http://www.postgresql.org/docs/8.1/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP
$condition .= ' OR '. $field .' ~* \''.'^(([a-z0-9]([a-z0-9\\-_]*\\.)+)('. LINK_DOMAINS .'|[a-z][a-z]))'.'\'';
}
else {
// mySQL requires backslashes to be double (triple?) escaped within character classes.
// See http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_regexp
$condition .= ' OR '. $field .' REGEXP \''.'^(([a-z0-9]([a-z0-9\\\-_]*\.)+)('. LINK_DOMAINS .'|[a-z][a-z]))'.'\'';
}
}
$where_conditions[] = $condition;
}
$this->query->add_where($this->options['group'], implode(' '. $this->operator .' ', $where_conditions));
}
/**
* Because more than one can be selected, we need to handle the value better.
*/
function admin_summary() {
if (!empty($this->options['exposed'])) {
return t('exposed');
}
$options = $this->operator_options('short');
$output = check_plain($options[$this->operator]);
if (in_array($this->operator, $this->operator_values(1))) {
$count = 0;
foreach ($this->value as $value) {
if (!$count) {
$output .= ' ' . check_plain($value);
}
else {
$output .= ', ' . check_plain($value);
}
$count++;
}
}
return $output;
}
}