Skip to content
......@@ -92,7 +92,7 @@ function file_theme() {
'variables' => array('file' => NULL, 'icon_directory' => NULL),
),
'file_icon' => array(
'variables' => array('file' => NULL, 'icon_directory' => NULL),
'variables' => array('file' => NULL, 'icon_directory' => NULL, 'alt' => ''),
),
'file_managed_file' => array(
'render element' => 'element',
......@@ -457,6 +457,17 @@ function file_managed_file_process($element, &$form_state, $form) {
'#markup' => theme('file_link', array('file' => $element['#file'])) . ' ',
'#weight' => -10,
);
// Anonymous users who have uploaded a temporary file need a
// non-session-based token added so file_managed_file_value() can check
// that they have permission to use this file on subsequent submissions of
// the same form (for example, after an Ajax upload or form validation
// error).
if (!$GLOBALS['user']->uid && $element['#file']->status != FILE_STATUS_PERMANENT) {
$element['fid_token'] = array(
'#type' => 'hidden',
'#value' => drupal_hmac_base64('file-' . $fid, drupal_get_private_key() . drupal_get_hash_salt()),
);
}
}
// Add the extension list to the page as JavaScript settings.
......@@ -529,14 +540,30 @@ function file_managed_file_value(&$element, $input = FALSE, $form_state = NULL)
// publicly accessible, with no download restrictions; for security
// reasons all other schemes must go through the file_download_access()
// check.
if (in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) || file_download_access($file->uri)) {
$fid = $file->fid;
}
// If the current user doesn't have access, don't let the file be
// changed.
else {
if (!in_array(file_uri_scheme($file->uri), variable_get('file_public_schema', array('public'))) && !file_download_access($file->uri)) {
$force_default = TRUE;
}
// Temporary files that belong to other users should never be allowed.
elseif ($file->status != FILE_STATUS_PERMANENT) {
if ($GLOBALS['user']->uid && $file->uid != $GLOBALS['user']->uid) {
$force_default = TRUE;
}
// Since file ownership can't be determined for anonymous users, they
// are not allowed to reuse temporary files at all. But they do need
// to be able to reuse their own files from earlier submissions of
// the same form, so to allow that, check for the token added by
// file_managed_file_process().
elseif (!$GLOBALS['user']->uid) {
$token = drupal_array_get_nested_value($form_state['input'], array_merge($element['#parents'], array('fid_token')));
if ($token !== drupal_hmac_base64('file-' . $file->fid, drupal_get_private_key() . drupal_get_hash_salt())) {
$force_default = TRUE;
}
}
}
// If all checks pass, allow the file to be changed.
if (!$force_default) {
$fid = $file->fid;
}
}
}
}
......@@ -749,7 +776,32 @@ function theme_file_link($variables) {
$icon_directory = $variables['icon_directory'];
$url = file_create_url($file->uri);
$icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));
// Human-readable names, for use as text-alternatives to icons.
$mime_name = array(
'application/msword' => t('Microsoft Office document icon'),
'application/vnd.ms-excel' => t('Office spreadsheet icon'),
'application/vnd.ms-powerpoint' => t('Office presentation icon'),
'application/pdf' => t('PDF icon'),
'video/quicktime' => t('Movie icon'),
'audio/mpeg' => t('Audio icon'),
'audio/wav' => t('Audio icon'),
'image/jpeg' => t('Image icon'),
'image/png' => t('Image icon'),
'image/gif' => t('Image icon'),
'application/zip' => t('Package icon'),
'text/html' => t('HTML icon'),
'text/plain' => t('Plain text icon'),
'application/octet-stream' => t('Binary Data'),
);
$mimetype = file_get_mimetype($file->uri);
$icon = theme('file_icon', array(
'file' => $file,
'icon_directory' => $icon_directory,
'alt' => !empty($mime_name[$mimetype]) ? $mime_name[$mimetype] : t('File'),
));
// Set options as per anchor format described at
// http://microformats.org/wiki/file-format-examples
......@@ -779,16 +831,19 @@ function theme_file_link($variables) {
* - file: A file object for which to make an icon.
* - icon_directory: (optional) A path to a directory of icons to be used for
* files. Defaults to the value of the "file_icon_directory" variable.
* - alt: (optional) The alternative text to represent the icon in text-based
* browsers. Defaults to an empty string.
*
* @ingroup themeable
*/
function theme_file_icon($variables) {
$file = $variables['file'];
$alt = $variables['alt'];
$icon_directory = $variables['icon_directory'];
$mime = check_plain($file->filemime);
$icon_url = file_icon_url($file, $icon_directory);
return '<img class="file-icon" alt="" title="' . $mime . '" src="' . $icon_url . '" />';
return '<img class="file-icon" alt="' . check_plain($alt) . '" title="' . $mime . '" src="' . $icon_url . '" />';
}
/**
......
......@@ -22,7 +22,7 @@ class FileFieldTestCase extends DrupalWebTestCase {
$modules[] = 'file';
$modules[] = 'file_module_test';
parent::setUp($modules);
$this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer nodes', 'bypass node access'));
$this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer users', 'administer permissions', 'administer content types', 'administer nodes', 'bypass node access', 'administer fields'));
$this->drupalLogin($this->admin_user);
}
......@@ -218,6 +218,30 @@ class FileFieldTestCase extends DrupalWebTestCase {
$message = isset($message) ? $message : format_string('File %file is permanent.', array('%file' => $file->uri));
$this->assertTrue($file->status == FILE_STATUS_PERMANENT, $message);
}
/**
* Creates a temporary file, for a specific user.
*
* @param string $data
* A string containing the contents of the file.
* @param int $uid
* The user ID of the file owner.
*
* @return object
* A file object, or FALSE on error.
*/
function createTemporaryFile($data, $uid = NULL) {
$file = file_save_data($data, NULL, NULL);
if ($file) {
$file->uid = isset($uid) ? $uid : $this->admin_user->uid;
// Change the file status to be temporary.
$file->status = NULL;
return file_save($file);
}
return $file;
}
}
/**
......@@ -526,6 +550,120 @@ class FileFieldWidgetTestCase extends FileFieldTestCase {
}
}
/**
* Tests exploiting the temporary file removal of another user using fid.
*/
function testTemporaryFileRemovalExploit() {
// Create a victim user.
$victim_user = $this->drupalCreateUser();
// Create an attacker user.
$attacker_user = $this->drupalCreateUser(array(
'access content',
'create page content',
'edit any page content',
));
// Log in as the attacker user.
$this->drupalLogin($attacker_user);
// Perform tests using the newly created users.
$this->doTestTemporaryFileRemovalExploit($victim_user->uid, $attacker_user->uid);
}
/**
* Tests exploiting the temporary file removal for anonymous users using fid.
*/
public function testTemporaryFileRemovalExploitAnonymous() {
// Set up an anonymous victim user.
$victim_uid = 0;
// Set up an anonymous attacker user.
$attacker_uid = 0;
// Set up permissions for anonymous attacker user.
user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
'access content' => TRUE,
'create page content' => TRUE,
'edit any page content' => TRUE,
));
// In order to simulate being the anonymous attacker user, we need to log
// out here since setUp() has logged in the admin.
$this->drupalLogout();
// Perform tests using the newly set up users.
$this->doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid);
}
/**
* Helper for testing exploiting the temporary file removal using fid.
*
* @param int $victim_uid
* The victim user ID.
* @param int $attacker_uid
* The attacker user ID.
*/
protected function doTestTemporaryFileRemovalExploit($victim_uid, $attacker_uid) {
// Use 'page' instead of 'article', so that the 'article' image field does
// not conflict with this test. If in the future the 'page' type gets its
// own default file or image field, this test can be made more robust by
// using a custom node type.
$type_name = 'page';
$field_name = 'test_file_field';
$this->createFileField($field_name, $type_name);
$test_file = $this->getTestFile('text');
foreach (array('nojs', 'js') as $type) {
// Create a temporary file owned by the anonymous victim user. This will be
// as if they had uploaded the file, but not saved the node they were
// editing or creating.
$victim_tmp_file = $this->createTemporaryFile('some text', $victim_uid);
$victim_tmp_file = file_load($victim_tmp_file->fid);
$this->assertTrue($victim_tmp_file->status != FILE_STATUS_PERMANENT, 'New file saved to disk is temporary.');
$this->assertFalse(empty($victim_tmp_file->fid), 'New file has a fid');
$this->assertEqual($victim_uid, $victim_tmp_file->uid, 'New file belongs to the victim user');
// Have attacker create a new node with a different uploaded file and
// ensure it got uploaded successfully.
// @todo Can we test AJAX? See https://www.drupal.org/node/2538260
$edit = array(
'title' => $type . '-title',
);
// Attach a file to a node.
$langcode = LANGUAGE_NONE;
$edit['files[' . $field_name . '_' . $langcode . '_0]'] = drupal_realpath($test_file->uri);
$this->drupalPost("node/add/$type_name", $edit, 'Save');
$node = $this->drupalGetNodeByTitle($edit['title']);
$node_file = file_load($node->{$field_name}[$langcode][0]['fid']);
$this->assertFileExists($node_file, 'New file saved to disk on node creation.');
$this->assertEqual($attacker_uid, $node_file->uid, 'New file belongs to the attacker.');
// Ensure the file can be downloaded.
$this->drupalGet(file_create_url($node_file->uri));
$this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
// "Click" the remove button (emulating either a nojs or js submission).
// In this POST request, the attacker "guesses" the fid of the victim's
// temporary file and uses that to remove this file.
$this->drupalGet('node/' . $node->nid . '/edit');
switch ($type) {
case 'nojs':
$this->drupalPost(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), 'Remove');
break;
case 'js':
$button = $this->xpath('//input[@type="submit" and @value="Remove"]');
$this->drupalPostAJAX(NULL, array("{$field_name}[$langcode][0][fid]" => (string) $victim_tmp_file->fid), array((string) $button[0]['name'] => (string) $button[0]['value']));
break;
}
// The victim's temporary file should not be removed by the attacker's
// POST request.
$this->assertFileExists($victim_tmp_file);
}
}
/**
* Tests upload and remove buttons for multiple multi-valued File fields.
*/
......@@ -1365,3 +1503,178 @@ class FilePrivateTestCase extends FileFieldTestCase {
$this->assertResponse(403, 'Confirmed that access is denied for the file without view field access permission after attempting to attach it to a new node.');
}
}
/**
* Confirm that file field submissions work correctly for anonymous visitors.
*/
class FileFieldAnonymousSubmission extends FileFieldTestCase {
public static function getInfo() {
return array(
'name' => 'File form anonymous submission',
'description' => 'Test anonymous form submission.',
'group' => 'File',
);
}
function setUp() {
parent::setUp();
// Allow node submissions by anonymous users.
user_role_grant_permissions(DRUPAL_ANONYMOUS_RID, array(
'create article content',
'access content',
));
}
/**
* Tests the basic node submission for an anonymous visitor.
*/
function testAnonymousNode() {
$bundle_label = 'Article';
$node_title = 'Test page';
// Load the node form.
$this->drupalGet('node/add/article');
$this->assertResponse(200, 'Loaded the article node form.');
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
$edit = array(
'title' => $node_title,
'body[und][0][value]' => 'Test article',
'body[und][0][format]' => 'filtered_html',
);
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertResponse(200);
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
$matches = array();
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
$nid = end($matches);
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
$node = node_load($nid);
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
}
}
/**
* Tests file submission for an anonymous visitor.
*/
function testAnonymousNodeWithFile() {
$bundle_label = 'Article';
$node_title = 'Test page';
// Load the node form.
$this->drupalGet('node/add/article');
$this->assertResponse(200, 'Loaded the article node form.');
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
// Generate an image file.
$image = $this->getTestImage();
// Submit the form.
$edit = array(
'title' => $node_title,
'body[und][0][value]' => 'Test article',
'body[und][0][format]' => 'filtered_html',
'files[field_image_und_0]' => drupal_realpath($image->uri),
);
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertResponse(200);
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
$matches = array();
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
$nid = end($matches);
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
$node = node_load($nid);
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
$this->assertEqual($node->field_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
}
}
/**
* Tests file submission for an anonymous visitor with a missing node title.
*/
function testAnonymousNodeWithFileWithoutTitle() {
$this->drupalLogout();
$this->_testNodeWithFileWithoutTitle();
}
/**
* Tests file submission for an authenticated user with a missing node title.
*/
function testAuthenticatedNodeWithFileWithoutTitle() {
$admin_user = $this->drupalCreateUser(array(
'bypass node access',
'access content overview',
'administer nodes',
));
$this->drupalLogin($admin_user);
$this->_testNodeWithFileWithoutTitle();
}
/**
* Helper method to test file submissions with missing node titles.
*/
protected function _testNodeWithFileWithoutTitle() {
$bundle_label = 'Article';
$node_title = 'Test page';
// Load the node form.
$this->drupalGet('node/add/article');
$this->assertResponse(200, 'Loaded the article node form.');
$this->assertText(strip_tags(t('Create @name', array('@name' => $bundle_label))));
// Generate an image file.
$image = $this->getTestImage();
// Submit the form but exclude the title field.
$edit = array(
'body[und][0][value]' => 'Test article',
'body[und][0][format]' => 'filtered_html',
'files[field_image_und_0]' => drupal_realpath($image->uri),
);
$this->drupalPost(NULL, $edit, t('Save'));
$this->assertResponse(200);
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
$this->assertNoText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
$this->assertText(t('!name field is required.', array('!name' => t('Title'))));
// Submit the form again but this time with the missing title field. This
// should still work.
$edit = array(
'title' => $node_title,
);
$this->drupalPost(NULL, $edit, t('Save'));
// Confirm the final submission actually worked.
$t_args = array('@type' => $bundle_label, '%title' => $node_title);
$this->assertText(strip_tags(t('@type %title has been created.', $t_args)), 'The node was created.');
$matches = array();
if (preg_match('@node/(\d+)$@', $this->getUrl(), $matches)) {
$nid = end($matches);
$this->assertNotEqual($nid, 0, 'The node ID was extracted from the URL.');
$node = node_load($nid);
$this->assertNotEqual($node, NULL, 'The node was loaded successfully.');
$this->assertEqual($node->field_image[LANGUAGE_NONE][0]['filename'], $image->filename, 'The image was uploaded successfully.');
}
}
/**
* Generates a test image.
*
* @return stdClass
* A file object.
*/
function getTestImage() {
// Get a file to upload.
$file = current($this->drupalGetTestFiles('image'));
// Add a filesize property to files as would be read by file_load().
$file->filesize = filesize($file->uri);
return $file;
}
}
......@@ -1497,7 +1497,7 @@ function _filter_url($text, $filter) {
$tasks['_filter_url_parse_full_links'] = $pattern;
// Match e-mail addresses.
$url_pattern = "[A-Za-z0-9._-]{1,254}@(?:$domain)";
$url_pattern = "[A-Za-z0-9._+-]{1,254}@(?:$domain)";
$pattern = "`($url_pattern)`";
$tasks['_filter_url_parse_email_links'] = $pattern;
......
......@@ -1120,8 +1120,12 @@ class FilterUnitTestCase extends DrupalUnitTestCase {
$f = filter_xss("<img src=\"jav\0a\0\0cript:alert(0)\">", array('img'));
$this->assertNoNormalized($f, 'cript', 'HTML scheme clearing evasion -- embedded nulls.');
$f = filter_xss('<img src=" &#14; javascript:alert(0)">', array('img'));
$this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
// @todo This dataset currently fails under 5.4 because of
// https://www.drupal.org/node/1210798. Restore after it's fixed.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$f = filter_xss('<img src=" &#14; javascript:alert(0)">', array('img'));
$this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
}
$f = filter_xss('<img src="vbscript:msgbox(0)">', array('img'));
$this->assertNoNormalized($f, 'vbscript', 'HTML scheme clearing evasion -- another scheme.');
......@@ -1294,6 +1298,7 @@ class FilterUnitTestCase extends DrupalUnitTestCase {
// Create a e-mail that is too long.
$long_email = str_repeat('a', 254) . '@example.com';
$too_long_email = str_repeat('b', 255) . '@example.com';
$email_with_plus_sign = 'one+two@example.com';
// Filter selection/pattern matching.
......@@ -1307,12 +1312,13 @@ http://example.com or www.example.com
),
// MAILTO URLs.
'
person@example.com or mailto:person2@example.com or ' . $long_email . ' but not ' . $too_long_email . '
person@example.com or mailto:person2@example.com or ' . $email_with_plus_sign . ' or ' . $long_email . ' but not ' . $too_long_email . '
' => array(
'<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
'<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
'<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
'<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
'<a href="mailto:' . $email_with_plus_sign . '">' . $email_with_plus_sign . '</a>' => TRUE,
),
// URI parts and special characters.
'
......
......@@ -801,6 +801,8 @@ function image_style_options($include_empty = TRUE, $output = CHECK_PLAIN) {
*
* @param $style
* The image style
* @param $scheme
* The file scheme, for example 'public' for public files.
*/
function image_style_deliver($style, $scheme) {
$args = func_get_args();
......@@ -833,8 +835,8 @@ function image_style_deliver($style, $scheme) {
file_download($scheme, file_uri_target($derivative_uri));
}
else {
$headers = module_invoke_all('file_download', $image_uri);
if (in_array(-1, $headers) || empty($headers)) {
$headers = file_download_headers($image_uri);
if (empty($headers)) {
return MENU_ACCESS_DENIED;
}
if (count($headers)) {
......
......@@ -32,7 +32,7 @@ class ImageFieldTestCase extends DrupalWebTestCase {
function setUp() {
parent::setUp('image');
$this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer content types', 'administer nodes', 'create article content', 'edit any article content', 'delete any article content', 'administer image styles'));
$this->admin_user = $this->drupalCreateUser(array('access content', 'access administration pages', 'administer site configuration', 'administer content types', 'administer nodes', 'create article content', 'edit any article content', 'delete any article content', 'administer image styles', 'administer fields'));
$this->drupalLogin($this->admin_user);
}
......@@ -201,6 +201,22 @@ class ImageStylesPathAndUrlTestCase extends DrupalWebTestCase {
$this->assertResponse(404, 'Accessing an image style URL with a source image that does not exist provides a 404 error response.');
}
/**
* Test that we do not pass an array to drupal_add_http_header.
*/
function testImageContentTypeHeaders() {
$files = $this->drupalGetTestFiles('image');
$file = array_shift($files);
// Copy the test file to private folder.
$private_file = file_copy($file, 'private://', FILE_EXISTS_RENAME);
// Tell image_module_test module to return the headers we want to test.
variable_set('image_module_test_invalid_headers', $private_file->uri);
// Invoke image_style_deliver so it will try to set headers.
$generated_url = image_style_url($this->style_name, $private_file->uri);
$this->drupalGet($generated_url);
variable_del('image_module_test_invalid_headers');
}
/**
* Test image_style_url().
*/
......@@ -269,7 +285,7 @@ class ImageStylesPathAndUrlTestCase extends DrupalWebTestCase {
$this->assertEqual($this->drupalGetHeader('Content-Length'), $generated_image_info['file_size'], 'Expected Content-Length was reported.');
if ($scheme == 'private') {
$this->assertEqual($this->drupalGetHeader('Expires'), 'Sun, 19 Nov 1978 05:00:00 GMT', 'Expires header was sent.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate, post-check=0, pre-check=0', 'Cache-Control header was set to prevent caching.');
$this->assertEqual($this->drupalGetHeader('Cache-Control'), 'no-cache, must-revalidate', 'Cache-Control header was set to prevent caching.');
$this->assertEqual($this->drupalGetHeader('X-Image-Owned-By'), 'image_module_test', 'Expected custom header has been added.');
// Make sure that a second request to the already existing derivate works
......
......@@ -9,6 +9,9 @@ function image_module_test_file_download($uri) {
if (variable_get('image_module_test_file_download', FALSE) == $uri) {
return array('X-Image-Owned-By' => 'image_module_test');
}
if (variable_get('image_module_test_invalid_headers', FALSE) == $uri) {
return array('Content-Type' => 'image/png');
}
}
/**
......
......@@ -1194,7 +1194,7 @@ function locale_translate_edit_form_submit($form, &$form_state) {
$translation = db_query("SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $key))->fetchField();
if (!empty($value)) {
// Only update or insert if we have a value to use.
if (!empty($translation)) {
if (is_string($translation)) {
db_update('locales_target')
->fields(array(
'translation' => $value,
......
......@@ -393,6 +393,16 @@ class LocaleTranslationFunctionalTest extends DrupalWebTestCase {
// The indicator should not be here.
$this->assertNoRaw($language_indicator, 'String is translated.');
// Verify that a translation set which has an empty target string can be
// updated without any database error.
db_update('locales_target')
->fields(array('translation' => ''))
->condition('language', $langcode, '=')
->condition('lid', $lid, '=')
->execute();
$this->drupalPost('admin/config/regional/translate/edit/' . $lid, $edit, t('Save translations'));
$this->assertText(t('The string has been saved.'), 'The string has been saved.');
// Try to edit a non-existent string and ensure we're redirected correctly.
// Assuming we don't have 999,999 strings already.
$random_lid = 999999;
......@@ -2237,6 +2247,37 @@ class LocaleContentFunctionalTest extends DrupalWebTestCase {
$this->drupalLogout();
}
/**
* Verifies that nodes may be created with different languages.
*/
function testNodeCreationWithLanguage() {
// Create an admin user and log them in.
$perms = array(
// Standard node permissions.
'create page content',
'administer content types',
'administer nodes',
'bypass node access',
// Locale.
'administer languages',
);
$web_user = $this->drupalCreateUser($perms);
$this->drupalLogin($web_user);
// Create some test nodes using different langcodes.
foreach (array(LANGUAGE_NONE, 'en', 'fr') as $langcode) {
$node_args = array(
'type' => 'page',
'promote' => 1,
'language' => $langcode,
);
$node = $this->drupalCreateNode($node_args);
$node_reloaded = node_load($node->nid, NULL, TRUE);
$this->assertEqual($node_reloaded->language, $langcode, format_string('The language code of the node was successfully set to @langcode.', array('@langcode' => $langcode)));
}
}
}
/**
......@@ -2629,6 +2670,68 @@ class LocaleUrlRewritingTest extends DrupalWebTestCase {
$this->drupalGet("$prefix/$path");
$this->assertResponse(404, $message2);
}
/**
* Check URL rewriting when using a domain name and a non-standard port.
*/
function testDomainNameNegotiationPort() {
$language_domain = 'example.fr';
$edit = array(
'locale_language_negotiation_url_part' => 1,
);
$this->drupalPost('admin/config/regional/language/configure/url', $edit, t('Save configuration'));
$edit = array(
'prefix' => '',
'domain' => $language_domain
);
$this->drupalPost('admin/config/regional/language/edit/fr', $edit, t('Save language'));
// Enable domain configuration.
variable_set('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN);
// Reset static caching.
drupal_static_reset('language_list');
drupal_static_reset('language_url_outbound_alter');
drupal_static_reset('language_url_rewrite_url');
// In case index.php is part of the URLs, we need to adapt the asserted
// URLs as well.
$index_php = strpos(url('', array('absolute' => TRUE)), 'index.php') !== FALSE;
// Remember current HTTP_HOST.
$http_host = $_SERVER['HTTP_HOST'];
// Fake a different port.
$_SERVER['HTTP_HOST'] .= ':88';
// Create an absolute French link.
$languages = language_list();
$language = $languages['fr'];
$url = url('', array(
'absolute' => TRUE,
'language' => $language
));
$expected = 'http://example.fr:88/';
$expected .= $index_php ? 'index.php/' : '';
$this->assertEqual($url, $expected, 'The right port is used.');
// If we set the port explicitly in url(), it should not be overriden.
$url = url('', array(
'absolute' => TRUE,
'language' => $language,
'base_url' => $GLOBALS['base_url'] . ':90',
));
$expected = 'http://example.fr:90/';
$expected .= $index_php ? 'index.php/' : '';
$this->assertEqual($url, $expected, 'A given port is not overriden.');
// Restore HTTP_HOST.
$_SERVER['HTTP_HOST'] = $http_host;
}
}
/**
......@@ -3141,3 +3244,46 @@ class LocaleCSSAlterTest extends DrupalWebTestCase {
$this->assertRaw('@import url("' . $base_url . '/modules/system/system.messages.css' . $query_string . '");' . "\n" . '@import url("' . $base_url . '/modules/system/system.messages-rtl.css' . $query_string . '");' . "\n", 'CSS: system.messages-rtl.css is added directly after system.messages.css.');
}
}
/**
* Tests locale translation safe string handling.
*/
class LocaleStringIsSafeTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Test if a string is safe',
'description' => 'Tests locale translation safe string handling.',
'group' => 'Locale',
);
}
function setUp() {
parent::setUp('locale');
}
/**
* Tests for locale_string_is_safe().
*/
public function testLocaleStringIsSafe() {
// Check a translatable string without HTML.
$string = 'Hello world!';
$result = locale_string_is_safe($string);
$this->assertTrue($result);
// Check a translatable string which includes trustable HTML.
$string = 'Hello <strong>world</strong>!';
$result = locale_string_is_safe($string);
$this->assertTrue($result);
// Check an untranslatable string which includes untrustable HTML (according
// to the locale_string_is_safe() function definition).
$string = 'Hello <img src="world.png" alt="world" />!';
$result = locale_string_is_safe($string);
$this->assertFalse($result);
// Check a translatable string which includes a token in an href attribute.
$string = 'Hi <a href="[current-user:url]">user</a>';
$result = locale_string_is_safe($string);
$this->assertTrue($result);
}
}
......@@ -281,6 +281,7 @@ function menu_edit_item($form, &$form_state, $type, $item, $menu) {
$form['link_title'] = array(
'#type' => 'textfield',
'#title' => t('Menu link title'),
'#maxlength' => 255,
'#default_value' => $item['link_title'],
'#description' => t('The text to be used for this link in the menu.'),
'#required' => TRUE,
......@@ -305,7 +306,7 @@ function menu_edit_item($form, &$form_state, $type, $item, $menu) {
'#title' => t('Path'),
'#maxlength' => 255,
'#default_value' => $path,
'#description' => t('The path for this menu link. This can be an internal Drupal path such as %add-node or an external URL such as %drupal. Enter %front to link to the front page.', array('%front' => '<front>', '%add-node' => 'node/add', '%drupal' => 'http://drupal.org')),
'#description' => t('The path for this menu link. This can be an internal path such as %add-node or an external URL such as %example. Enter %front to link to the front page.', array('%front' => '<front>', '%add-node' => 'node/add', '%example' => 'http://example.com')),
'#required' => TRUE,
);
$form['actions']['delete'] = array(
......
......@@ -674,6 +674,7 @@ function menu_form_node_form_alter(&$form, $form_state) {
$form['menu']['link']['link_title'] = array(
'#type' => 'textfield',
'#title' => t('Menu link title'),
'#maxlength' => 255,
'#default_value' => $link['link_title'],
);
......
......@@ -648,7 +648,12 @@ class MenuNodeTestCase extends DrupalWebTestCase {
);
$this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
// Create a node.
// Verify that the menu link title on the node add form has the correct
// maxlength.
$this->drupalGet('node/add/page');
$this->assertPattern('/<input .* id="edit-menu-link-title" .* maxlength="255" .* \/>/', 'Menu link title field has correct maxlength in node add form.');
// Create a node with menu link disabled.
$node_title = $this->randomName();
$language = LANGUAGE_NONE;
$edit = array(
......@@ -684,6 +689,10 @@ class MenuNodeTestCase extends DrupalWebTestCase {
$this->drupalGet('node/' . $node->nid . '/edit');
$this->assertOptionSelected('edit-menu-weight', 17, 'Menu weight correct in edit form');
// Verify that the menu link title on the node edit form has the correct
// maxlength.
$this->assertPattern('/<input .* id="edit-menu-link-title" .* maxlength="255" .* \/>/', 'Menu link title field has correct maxlength in node edit form.');
// Edit the node and remove the menu link.
$edit = array(
'menu[enabled]' => FALSE,
......
......@@ -11,7 +11,7 @@
function node_overview_types() {
$types = node_type_get_types();
$names = node_type_get_names();
$field_ui = module_exists('field_ui');
$field_ui = module_exists('field_ui') && user_access('administer fields');
$header = array(t('Name'), array('data' => t('Operations'), 'colspan' => $field_ui ? '4' : '2'));
$rows = array();
......
......@@ -329,6 +329,8 @@ function _node_mass_update_helper($nid, $updates) {
}
/**
* Implements callback_batch_operation().
*
* Executes a batch operation for node_mass_update().
*
* @param array $nodes
......@@ -367,7 +369,9 @@ function _node_mass_update_batch_process($nodes, $updates, &$context) {
}
/**
* Menu callback: Reports the status of batch operation for node_mass_update().
* Implements callback_batch_finished().
*
* Reports the status of batch operation for node_mass_update().
*
* @param bool $success
* A boolean indicating whether the batch mass update operation successfully
......@@ -504,14 +508,17 @@ function node_admin_nodes() {
$options = array();
foreach ($nodes as $node) {
$langcode = entity_language('node', $node);
$l_options = $langcode != LANGUAGE_NONE && isset($languages[$langcode]) ? array('language' => $languages[$langcode]) : array();
$uri = entity_uri('node', $node);
if ($langcode != LANGUAGE_NONE && isset($languages[$langcode])) {
$uri['options']['language'] = $languages[$langcode];
}
$options[$node->nid] = array(
'title' => array(
'data' => array(
'#type' => 'link',
'#title' => $node->title,
'#href' => 'node/' . $node->nid,
'#options' => $l_options,
'#href' => $uri['path'],
'#options' => $uri['options'],
'#suffix' => ' ' . theme('mark', array('type' => node_mark($node->nid, $node->changed))),
),
),
......
......@@ -1084,19 +1084,9 @@ function hook_delete($node) {
* @ingroup node_api_hooks
*/
function hook_prepare($node) {
$file = file_save_upload($field_name, _image_filename($file->filename, NULL, TRUE));
if ($file) {
if (!image_get_info($file->uri)) {
form_set_error($field_name, t('Uploaded file is not a valid image'));
return;
}
}
else {
return;
if (!isset($node->mymodule_value)) {
$node->mymodule_value = 'foo';
}
$node->images['_original'] = $file->uri;
_image_build_derivatives($node, TRUE);
$node->new_file = TRUE;
}
/**
......
......@@ -410,6 +410,7 @@ function node_schema() {
'nid' => array(
'description' => 'The {node}.nid that was read.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
......@@ -943,6 +944,23 @@ function node_update_7015() {
->execute();
}
/**
* Change {history}.nid to an unsigned int in order to match {node}.nid.
*/
function node_update_7016() {
db_drop_primary_key('history');
db_drop_index('history', 'nid');
db_change_field('history', 'nid', 'nid', array(
'description' => 'The {node}.nid that was read.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
));
db_add_primary_key('history', array('uid', 'nid'));
db_add_index('history', 'nid', array('nid'));
}
/**
* @} End of "addtogroup updates-7.x-extra".
*/
......@@ -2953,7 +2953,10 @@ function node_search_validate($form, &$form_state) {
* system. When adding a node listing to your module, be sure to use a dynamic
* query created by db_select() and add a tag of "node_access". This will allow
* modules dealing with node access to ensure only nodes to which the user has
* access are retrieved, through the use of hook_query_TAG_alter().
* access are retrieved, through the use of hook_query_TAG_alter(). Tagging a
* query with "node_access" does not check the published/unpublished status of
* nodes, so the base query is responsible for ensuring that unpublished nodes
* are not displayed to inappropriate users.
*
* Note: Even a single module returning NODE_ACCESS_DENY from hook_node_access()
* will block access to the node. Therefore, implementers should take care to
......@@ -3669,6 +3672,8 @@ function node_access_rebuild($batch_mode = FALSE) {
}
/**
* Implements callback_batch_operation().
*
* Performs batch operation for node_access_rebuild().
*
* This is a multistep operation: we go through all nodes by packs of 20. The
......@@ -3683,7 +3688,7 @@ function _node_access_rebuild_batch_operation(&$context) {
// Initiate multistep processing.
$context['sandbox']['progress'] = 0;
$context['sandbox']['current_node'] = 0;
$context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
$context['sandbox']['max'] = db_query('SELECT COUNT(nid) FROM {node}')->fetchField();
}
// Process the next 20 nodes.
......@@ -3707,6 +3712,8 @@ function _node_access_rebuild_batch_operation(&$context) {
}
/**
* Implements callback_batch_finished().
*
* Performs post-processing for node_access_rebuild().
*
* @param bool $success
......
......@@ -396,7 +396,6 @@ function node_preview($node) {
$cloned_node->changed = REQUEST_TIME;
$nodes = array($cloned_node->nid => $cloned_node);
field_attach_prepare_view('node', $nodes, 'full');
// Display a preview of the node.
if (!form_get_errors()) {
......
......@@ -457,10 +457,70 @@ class PagePreviewTestCase extends DrupalWebTestCase {
}
function setUp() {
parent::setUp();
parent::setUp(array('taxonomy', 'node'));
$web_user = $this->drupalCreateUser(array('edit own page content', 'create page content'));
$this->drupalLogin($web_user);
// Add a vocabulary so we can test different view modes.
$vocabulary = (object) array(
'name' => $this->randomName(),
'description' => $this->randomName(),
'machine_name' => drupal_strtolower($this->randomName()),
'help' => '',
'nodes' => array('page' => 'page'),
);
taxonomy_vocabulary_save($vocabulary);
$this->vocabulary = $vocabulary;
// Add a term to the vocabulary.
$term = (object) array(
'name' => $this->randomName(),
'description' => $this->randomName(),
// Use the first available text format.
'format' => db_query_range('SELECT format FROM {filter_format}', 0, 1)->fetchField(),
'vid' => $this->vocabulary->vid,
'vocabulary_machine_name' => $vocabulary->machine_name,
);
taxonomy_term_save($term);
$this->term = $term;
// Set up a field and instance.
$this->field_name = drupal_strtolower($this->randomName());
$this->field = array(
'field_name' => $this->field_name,
'type' => 'taxonomy_term_reference',
'settings' => array(
'allowed_values' => array(
array(
'vocabulary' => $this->vocabulary->machine_name,
'parent' => '0',
),
),
)
);
field_create_field($this->field);
$this->instance = array(
'field_name' => $this->field_name,
'entity_type' => 'node',
'bundle' => 'page',
'widget' => array(
'type' => 'options_select',
),
// Hide on full display but render on teaser.
'display' => array(
'default' => array(
'type' => 'hidden',
),
'teaser' => array(
'type' => 'taxonomy_term_reference_link',
),
),
);
field_create_instance($this->instance);
}
/**
......@@ -470,21 +530,26 @@ class PagePreviewTestCase extends DrupalWebTestCase {
$langcode = LANGUAGE_NONE;
$title_key = "title";
$body_key = "body[$langcode][0][value]";
$term_key = "{$this->field_name}[$langcode]";
// Fill in node creation form and preview node.
$edit = array();
$edit[$title_key] = $this->randomName(8);
$edit[$body_key] = $this->randomName(16);
$edit[$term_key] = $this->term->tid;
$this->drupalPost('node/add/page', $edit, t('Preview'));
// Check that the preview is displaying the title and body.
// Check that the preview is displaying the title, body, and term.
$this->assertTitle(t('Preview | Drupal'), 'Basic page title is preview.');
$this->assertText($edit[$title_key], 'Title displayed.');
$this->assertText($edit[$body_key], 'Body displayed.');
$this->assertText($this->term->name, 'Term displayed.');
// Check that the title and body fields are displayed with the correct values.
// Check that the title, body, and term fields are displayed with the
// correct values.
$this->assertFieldByName($title_key, $edit[$title_key], 'Title field displayed.');
$this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.');
$this->assertFieldByName($term_key, $edit[$term_key], 'Term field displayed.');
}
/**
......@@ -494,6 +559,7 @@ class PagePreviewTestCase extends DrupalWebTestCase {
$langcode = LANGUAGE_NONE;
$title_key = "title";
$body_key = "body[$langcode][0][value]";
$term_key = "{$this->field_name}[$langcode]";
// Force revision on "Basic page" content.
variable_set('node_options_page', array('status', 'revision'));
......@@ -501,17 +567,21 @@ class PagePreviewTestCase extends DrupalWebTestCase {
$edit = array();
$edit[$title_key] = $this->randomName(8);
$edit[$body_key] = $this->randomName(16);
$edit[$term_key] = $this->term->tid;
$edit['log'] = $this->randomName(32);
$this->drupalPost('node/add/page', $edit, t('Preview'));
// Check that the preview is displaying the title and body.
// Check that the preview is displaying the title, body, and term.
$this->assertTitle(t('Preview | Drupal'), 'Basic page title is preview.');
$this->assertText($edit[$title_key], 'Title displayed.');
$this->assertText($edit[$body_key], 'Body displayed.');
$this->assertText($this->term->name, 'Term displayed.');
// Check that the title and body fields are displayed with the correct values.
// Check that the title, body, and term fields are displayed with the
// correct values.
$this->assertFieldByName($title_key, $edit[$title_key], 'Title field displayed.');
$this->assertFieldByName($body_key, $edit[$body_key], 'Body field displayed.');
$this->assertFieldByName($term_key, $edit[$term_key], 'Term field displayed.');
// Check that the log field has the correct value.
$this->assertFieldByName('log', $edit['log'], 'Log field displayed.');
......@@ -1448,7 +1518,7 @@ class NodeTypeTestCase extends DrupalWebTestCase {
* Tests editing a node type using the UI.
*/
function testNodeTypeEditing() {
$web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types'));
$web_user = $this->drupalCreateUser(array('bypass node access', 'administer content types', 'administer fields'));
$this->drupalLogin($web_user);
$instance = field_info_instance('node', 'body', 'page');
......@@ -2698,8 +2768,8 @@ class NodeAccessFieldTestCase extends NodeWebTestCase {
node_access_rebuild();
// Create some users.
$this->admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
$this->content_admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));
$this->admin_user = $this->drupalCreateUser(array('access content', 'bypass node access', 'administer fields'));
$this->content_admin_user = $this->drupalCreateUser(array('access content', 'administer content types', 'administer fields'));
// Add a custom field to the page content type.
$this->field_name = drupal_strtolower($this->randomName() . '_field_name');
......@@ -2916,3 +2986,36 @@ class NodePageCacheTest extends NodeWebTestCase {
$this->assertResponse(404);
}
}
/**
* Tests that multi-byte UTF-8 characters are stored and retrieved correctly.
*/
class NodeMultiByteUtf8Test extends NodeWebTestCase {
public static function getInfo() {
return array(
'name' => 'Multi-byte UTF-8',
'description' => 'Test that multi-byte UTF-8 characters are stored and retrieved correctly.',
'group' => 'Node',
);
}
/**
* Tests that multi-byte UTF-8 characters are stored and retrieved correctly.
*/
public function testMultiByteUtf8() {
$connection = Database::getConnection();
// On MySQL, this test will only run if 'charset' is set to 'utf8mb4' in
// settings.php.
if (!($connection->utf8mb4IsSupported() && $connection->utf8mb4IsActive())) {
return;
}
$title = '🐙';
$this->assertTrue(drupal_strlen($title, 'utf-8') < strlen($title), 'Title has multi-byte characters.');
$node = $this->drupalCreateNode(array('title' => $title));
$this->drupalGet('node/' . $node->nid);
$result = $this->xpath('//h1[@id="page-title"]');
$this->assertEqual(trim((string) $result[0]), $title, 'The passed title was returned.');
}
}
......@@ -680,11 +680,11 @@ class OpenIDTestCase extends DrupalWebTestCase {
* Test _openid_dh_XXX_to_XXX() functions.
*/
function testConversion() {
$this->assertEqual(_openid_dh_long_to_base64('12345678901234567890123456789012345678901234567890'), 'CHJ/Y2mq+DyhUCZ0evjH8ZbOPwrS', '_openid_dh_long_to_base64() returned expected result.');
$this->assertEqual(_openid_dh_base64_to_long('BsH/g8Nrpn2dtBSdu/sr1y8hxwyx'), '09876543210987654321098765432109876543210987654321', '_openid_dh_base64_to_long() returned expected result.');
$this->assertIdentical(_openid_dh_long_to_base64('12345678901234567890123456789012345678901234567890'), 'CHJ/Y2mq+DyhUCZ0evjH8ZbOPwrS', '_openid_dh_long_to_base64() returned expected result.');
$this->assertIdentical(_openid_dh_base64_to_long('BsH/g8Nrpn2dtBSdu/sr1y8hxwyx'), '9876543210987654321098765432109876543210987654321', '_openid_dh_base64_to_long() returned expected result.');
$this->assertEqual(_openid_dh_long_to_binary('12345678901234567890123456789012345678901234567890'), "\x08r\x7fci\xaa\xf8<\xa1P&tz\xf8\xc7\xf1\x96\xce?\x0a\xd2", '_openid_dh_long_to_binary() returned expected result.');
$this->assertEqual(_openid_dh_binary_to_long("\x06\xc1\xff\x83\xc3k\xa6}\x9d\xb4\x14\x9d\xbb\xfb+\xd7/!\xc7\x0c\xb1"), '09876543210987654321098765432109876543210987654321', '_openid_dh_binary_to_long() returned expected result.');
$this->assertIdentical(_openid_dh_long_to_binary('12345678901234567890123456789012345678901234567890'), "\x08r\x7fci\xaa\xf8<\xa1P&tz\xf8\xc7\xf1\x96\xce?\x0a\xd2", '_openid_dh_long_to_binary() returned expected result.');
$this->assertIdentical(_openid_dh_binary_to_long("\x06\xc1\xff\x83\xc3k\xa6}\x9d\xb4\x14\x9d\xbb\xfb+\xd7/!\xc7\x0c\xb1"), '9876543210987654321098765432109876543210987654321', '_openid_dh_binary_to_long() returned expected result.');
}
/**
......