diff --git a/core/MAINTAINERS.txt b/core/MAINTAINERS.txt
index 8f8edb2..1630b3b 100644
--- a/core/MAINTAINERS.txt
+++ b/core/MAINTAINERS.txt
@@ -118,10 +118,6 @@ Path system
 - Dave Reid 'davereid' http://drupal.org/user/53892
 - Nathaniel Catchpole 'catch' http://drupal.org/user/35733
 
-Plugin system
-- Kris Vanderwater 'EclipseGc' http://drupal.org/user/61203
-- Alex Bronstein 'effulgentsia' http://drupal.org/user/78040
-
 Render system
 - Moshe Weitzman 'moshe weitzman' http://drupal.org/user/23
 - Alex Bronstein 'effulgentsia' http://drupal.org/user/78040
@@ -207,6 +203,10 @@ Database Logging module
 Edit module
 - Wim Leers 'Wim Leers' http://drupal.org/user/99777
 
+Entity Reference module
+- Amitai Burstein 'Amitaibu' http://drupal.org/user/57511
+- Andrei Mateescu 'amateescu' http://drupal.org/user/729614
+
 Field module
 - Yves Chedemois 'yched' http://drupal.org/user/39567
 - Barry Jaspan 'bjaspan' http://drupal.org/user/46413
diff --git a/core/includes/ajax.inc b/core/includes/ajax.inc
index a7fbe7b..f0dca74 100644
--- a/core/includes/ajax.inc
+++ b/core/includes/ajax.inc
@@ -251,8 +251,8 @@ function ajax_render($commands = array()) {
       //   reliably diffed with array_diff_key(), since the number can change
       //   due to factors unrelated to the inline content, so for now, we strip
       //   the inline items from Ajax responses, and can add support for them
-      //   when drupal_add_css() and drupal_add_js() are changed to use a hash
-      //   of the inline content as the array key.
+      //   when drupal_add_css() and drupal_add_js() are changed to using md5()
+      //   or some other hash of the inline content.
       foreach ($items[$type] as $key => $item) {
         if (is_numeric($key)) {
           unset($items[$type][$key]);
diff --git a/core/includes/config.inc b/core/includes/config.inc
index 20e6bb4..1453ade 100644
--- a/core/includes/config.inc
+++ b/core/includes/config.inc
@@ -182,8 +182,6 @@ function config_sync_changes(array $config_changes, StorageInterface $source_sto
   $factory = drupal_container()->get('config.factory');
   foreach (array('delete', 'create', 'change') as $op) {
     foreach ($config_changes[$op] as $name) {
-      // Validate the configuration object name before importing it.
-      Config::validateName($name);
       if ($op == 'delete') {
         $target_storage->delete($name);
       }
@@ -258,8 +256,6 @@ function config_import_invoke_owner(array $config_changes, StorageInterface $sou
       // Call to the configuration entity's storage controller to handle the
       // configuration change.
       $handled_by_module = FALSE;
-      // Validate the configuration object name before importing it.
-      Config::validateName($name);
       if ($entity_type = config_get_entity_type_by_name($name)) {
         $old_config = new Config($name, $target_storage);
         $old_config->load();
diff --git a/core/includes/form.inc b/core/includes/form.inc
index 7507234..a855434 100644
--- a/core/includes/form.inc
+++ b/core/includes/form.inc
@@ -3994,14 +3994,6 @@ function form_process_vertical_tabs($element, &$form_state) {
     '#parents' => $element['#parents'],
   );
 
-  // Add an invisible label for accessibility.
-  if (!isset($element['#title'])) {
-    $element['#title'] = t('Vertical Tabs');
-    $element['#title_display'] = 'invisible';
-  }
-
-  $element['#attached']['library'][] = array('system', 'drupal.vertical-tabs');
-
   // The JavaScript stores the currently selected tab in this hidden
   // field so that the active tab can be restored the next time the
   // form is rendered, e.g. on preview pages or when form validation
@@ -4020,25 +4012,6 @@ function form_process_vertical_tabs($element, &$form_state) {
 }
 
 /**
- * Prepares a vertical_tabs element for rendering.
- *
- * @param array $element
- *   An associative array containing the properties and children of the
- *   vertical tabs element.
- *
- * @return array
- *   The modified element.
- */
-function form_pre_render_vertical_tabs($element) {
-  // Do not render the vertical tabs element if it is empty.
-  $group = implode('][', $element['#parents']);
-  if (!element_get_visible_children($element['group']['#groups'][$group])) {
-    $element['#printed'] = TRUE;
-  }
-  return $element;
-}
-
-/**
  * Returns HTML for an element's children details as vertical tabs.
  *
  * @param $variables
@@ -4050,7 +4023,26 @@ function form_pre_render_vertical_tabs($element) {
  */
 function theme_vertical_tabs($variables) {
   $element = $variables['element'];
-  return '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
+  // Even if there are no tabs the element will still have a child element for
+  // the active tab. We need to iterate over the tabs to ascertain if any
+  // are visible before showing the wrapper and h2.
+  $visible_tab = FALSE;
+  $output = '';
+  foreach (element_children($element['group']) as $tab_index) {
+    if (!isset($element['group'][$tab_index]['#access']) ||
+        !empty($element['group'][$tab_index]['#access'])) {
+      $visible_tab = TRUE;
+      break;
+    }
+  }
+  if ($visible_tab) {
+    // Add required JavaScript and Stylesheet.
+    drupal_add_library('system', 'drupal.vertical-tabs');
+
+    $output = '<h2 class="element-invisible">' . t('Vertical Tabs') . '</h2>';
+    $output .= '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
+  }
+  return $output;
 }
 
 /**
diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc
index 4ec640d..8f5dd68 100644
--- a/core/includes/install.core.inc
+++ b/core/includes/install.core.inc
@@ -154,9 +154,6 @@ function install_state_defaults() {
     // This becomes TRUE only when a valid database connection can be
     // established.
     'database_verified' => FALSE,
-    // Whether a translation file for the selected language will be downloaded
-    // from the translation server.
-    'download_translation' => FALSE,
     // An array of forms to be programmatically submitted during the
     // installation. The keys of each element indicate the name of the
     // installation task that the form submission is for, and the values are
@@ -173,6 +170,8 @@ function install_state_defaults() {
     // Whether or not this installation is interactive. By default this will
     // be set to FALSE if settings are passed in to install_drupal().
     'interactive' => TRUE,
+    // An array of available translation files for the installation.
+    'translations' => array(),
     // An array of parameters for the installation, pre-populated by the URL
     // or by the settings passed in to install_drupal(). This is primarily
     // used to store 'profile' (the name of the chosen installation profile)
@@ -193,10 +192,6 @@ function install_state_defaults() {
     // $_SERVER array via drupal_override_server_variables(). Used by
     // non-interactive installations only.
     'server' => array(),
-    // The server URL where the interface translation files can be downloaded.
-    // Tokens in the pattern will be replaced by appropriate values for the
-    // required translation file.
-    'server_pattern' => 'http://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po',
     // This becomes TRUE only when a valid settings.php file is written
     // (containing both valid database connection information and a valid
     // config directory).
@@ -223,9 +218,6 @@ function install_state_defaults() {
     // A list of installation tasks which have already been performed during
     // the current page request.
     'tasks_performed' => array(),
-    // An array of translation files URIs available for the installation. Keyed
-    // by the translation language code.
-    'translations' => array(),
   );
   return $defaults;
 }
@@ -617,14 +609,8 @@ function install_tasks_to_perform($install_state) {
  *   A list of tasks, with associated metadata.
  */
 function install_tasks($install_state) {
-  // Determine whether a translation file must be imported during the
-  // 'install_import_translations' task. Import when a non-English language is
-  // available and selected.
+  // Determine whether translation import tasks will need to be performed.
   $needs_translations = count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en';
-  // Determine whether a translation file must be downloaded during the
-  // 'install_download_translation' task. Download when a non-English language
-  // is selected, but no translation is yet in the translations directory.
-  $needs_download = isset($install_state['parameters']['langcode']) && !isset($install_state['translations'][$install_state['parameters']['langcode']]) && $install_state['parameters']['langcode'] != 'en';
 
   // Start with the core installation tasks that run before handing control
   // to the installation profile.
@@ -633,9 +619,6 @@ function install_tasks($install_state) {
       'display_name' => st('Choose language'),
       'run' => INSTALL_TASK_RUN_IF_REACHED,
     ),
-    'install_download_translation' => array(
-      'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
-    ),
     'install_select_profile' => array(
       'display_name' => st('Choose profile'),
       'display' => count($install_state['profiles']) != 1,
@@ -841,6 +824,10 @@ function install_display_output($output, $install_state) {
  *
  * @return
  *   A themed status report, or an exception if there are requirement errors.
+ *   If there are only requirement warnings, a themed status report is shown
+ *   initially, but the user is allowed to bypass it by providing 'continue=1'
+ *   in the URL. Otherwise, no output is returned, so that the next task can be
+ *   run in the same page request.
  */
 function install_verify_requirements(&$install_state) {
   // Check the installation requirements for Drupal and this profile.
@@ -849,7 +836,35 @@ function install_verify_requirements(&$install_state) {
   // Verify existence of all required modules.
   $requirements += drupal_verify_profile($install_state);
 
-  return install_display_requirements($install_state, $requirements);
+  // Check the severity of the requirements reported.
+  $severity = drupal_requirements_severity($requirements);
+
+  // If there are errors, always display them. If there are only warnings, skip
+  // them if the user has provided a URL parameter acknowledging the warnings
+  // and indicating a desire to continue anyway. See drupal_requirements_url().
+  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
+    if ($install_state['interactive']) {
+      drupal_set_title(st('Requirements problem'));
+      $status_report = theme('status_report', array('requirements' => $requirements));
+      $status_report .= st('Check the messages and <a href="!url">try again</a>.', array('!url' => check_url(drupal_requirements_url($severity))));
+      return $status_report;
+    }
+    else {
+      // Throw an exception showing any unmet requirements.
+      $failures = array();
+      foreach ($requirements as $requirement) {
+        // Skip warnings altogether for non-interactive installations; these
+        // proceed in a single request so there is no good opportunity (and no
+        // good method) to warn the user anyway.
+        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
+          $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
+        }
+      }
+      if (!empty($failures)) {
+        throw new Exception(implode("\n\n", $failures));
+      }
+    }
+  }
 }
 
 /**
@@ -1247,26 +1262,26 @@ function install_select_profile_form($form, &$form_state, $install_state) {
  * Finds all .po files that are useful to the installer.
  *
  * @return
- *   An associative array of file URIs keyed by language code. URIs as
- *   returned by file_scan_directory().
+ *   An associative array of file information objects keyed by file URIs as
+ *   returned by file_scan_directory(). English is removed from the array and
+ *   the object is prepared for database insertion.
  *
  * @see file_scan_directory()
  */
 function install_find_translations() {
-  $translations = array();
   $files = install_find_translation_files();
   // English does not need a translation file.
   array_unshift($files, (object) array('name' => 'en'));
-  foreach ($files as $uri => $file) {
+  foreach ($files as $key => $file) {
     // Strip off the file name component before the language code.
-    $langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
+    $files[$key]->langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
     // Language codes cannot exceed 12 characters to fit into the {language}
     // table.
-    if (strlen($langcode) <= 12) {
-      $translations[$langcode] = $uri;
+    if (strlen($files[$key]->langcode) > 12) {
+      unset($files[$key]);
     }
   }
-  return $translations;
+  return $files;
 }
 
 /**
@@ -1304,46 +1319,66 @@ function install_find_translation_files($langcode = NULL) {
  *   language cannot be chosen automatically.
  */
 function install_select_language(&$install_state) {
-  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
-
-  // Find all available translation files.
+  // Find all available translations.
   $files = install_find_translations();
   $install_state['translations'] += $files;
 
-  // If a valid language code is set, continue with the next installation step.
-  // When translations from the localization server are used, any language code
-  // is accepted because the standard language list is kept in sync with the
-  // langauges available at http://localize.drupal.org.
-  // When files from the translation directory are used, we only accept
-  // languages for which a file is available.
   if (!empty($_POST['langcode'])) {
-    $standard_languages = standard_language_list();
-    $langcode = $_POST['langcode'];
-    if ($langcode == 'en' || isset($files[$langcode]) || isset($standard_languages[$langcode])) {
-      $install_state['parameters']['langcode'] = $langcode;
-      return;
+    foreach ($files as $file) {
+      if ($_POST['langcode'] == $file->langcode) {
+        $install_state['parameters']['langcode'] = $file->langcode;
+        return;
+      }
     }
   }
 
   if (empty($install_state['parameters']['langcode'])) {
-    // If we are performing an interactive installation, we display a form to
-    // select a right language. If no translation files were found in the
-    // translations directory, the form shows a list of standard languages. If
-    // translation files were found the form shows a select list of the
-    // corresponding languages to choose from.
-    if ($install_state['interactive']) {
-      drupal_set_title(st('Choose language'));
-      include_once DRUPAL_ROOT . '/core/includes/form.inc';
-      $elements = drupal_get_form('install_select_language_form', count($files) > 1 ? $files : array());
-      return drupal_render($elements);
+    // If only the built-in (English) language is available, and we are
+    // performing an interactive installation, inform the user that the
+    // installer can be translated. Otherwise we assume the user knows what he
+    // is doing.
+    if (count($files) == 1) {
+      if ($install_state['interactive']) {
+        $directory = variable_get('locale_translate_file_directory', conf_path() . '/files/translations');
+
+        drupal_set_title(st('Choose language'));
+        if (!empty($install_state['parameters']['translate'])) {
+          $output = '<p>Follow these steps to translate Drupal into your language:</p>';
+          $output .= '<ol>';
+          $output .= '<li>Download a translation from the <a href="http://localize.drupal.org/download">translation server</a>.</li>';
+          $output .= '<li>Place it into the following directory:<pre>' . $directory . '</pre></li>';
+          $output .= '</ol>';
+          $output .= '<p>For more information on installing Drupal in different languages, visit the <a href="http://drupal.org/localize" target="_blank">drupal.org handbook page</a>.</p>';
+          $output .= '<p>How should the installation continue?</p>';
+          $output .= '<ul>';
+          $output .= '<li><a href="' . check_url(drupal_current_script_url(array('translate' => NULL))) . '">Reload the language selection page after adding translations</a></li>';
+          $output .= '<li><a href="' . check_url(drupal_current_script_url(array('langcode' => 'en', 'translate' => NULL))) . '">Continue installation in English</a></li>';
+          $output .= '</ul>';
+        }
+        else {
+          include_once DRUPAL_ROOT . '/core/includes/form.inc';
+          $elements = drupal_get_form('install_select_language_form', $files);
+          $output = drupal_render($elements);
+        }
+        return $output;
+      }
+      // One language, but not an interactive installation. Assume the user
+      // knows what he is doing.
+      $file = current($files);
+      $install_state['parameters']['langcode'] = $file->langcode;
+      return;
     }
-    // If we are performing a non-interactive installation. If only one language
-    // (English) is available, assume the user knows what he is doing. Otherwise
-    // thow an error.
     else {
-      if (count($files) == 1) {
-        $install_state['parameters']['langcode'] = array_shift(array_keys($files));
-        return;
+      // We still don't have a langcode, so display a form for selecting one.
+      // Only do this in the case of interactive installations, since this is
+      // not a real form with submit handlers (the database isn't even set up
+      // yet), rather just a convenience method for setting parameters in the
+      // URL.
+      if ($install_state['interactive']) {
+        drupal_set_title(st('Choose language'));
+        include_once DRUPAL_ROOT . '/core/includes/form.inc';
+        $elements = drupal_get_form('install_select_language_form', $files);
+        return drupal_render($elements);
       }
       else {
         throw new Exception(st('Sorry, you must select a language to continue the installation.'));
@@ -1355,45 +1390,38 @@ function install_select_language(&$install_state) {
 /**
  * Form constructor for the language selection form.
  *
- * @param array $files
- *   (optional) An associative array of file URIs keyed by language code as
- *   returned by file_scan_directory(). Defaults to all standard languages.
+ * @param $files
+ *   An associative array of file information objects keyed by file URIs as
+ *   returned by file_scan_directory().
  *
  * @see file_scan_directory()
  * @ingroup forms
  */
-function install_select_language_form($form, &$form_state, $files = array()) {
+function install_select_language_form($form, &$form_state, $files) {
   include_once DRUPAL_ROOT . '/core/includes/standard.inc';
   include_once DRUPAL_ROOT . '/core/modules/language/language.module';
   include_once DRUPAL_ROOT . '/core/modules/language/language.negotiation.inc';
 
   $standard_languages = standard_language_list();
   $select_options = array();
-  $browser_options = array();
-
-  // Build a select list with language names in native language for the user
-  // to choose from. And build a list of available languages for the browser
-  // to select the language default from.
-  if (count($files)) {
-    // Select lists based on available language files.
-    foreach ($files as $langcode => $uri) {
-      $select_options[$langcode] = isset($standard_languages[$langcode]) ? $standard_languages[$langcode][1] : $langcode;
-      $browser_options[$langcode] = new Language(array(
-        'langcode' => $langcode,
-      ));
+  $languages = array();
+
+  foreach ($files as $file) {
+    if (isset($standard_languages[$file->langcode])) {
+      // Build a list of select list options based on files we found.
+      $select_options[$file->langcode] = $standard_languages[$file->langcode][1];
     }
-  }
-  else {
-    // Select lists based on all standard languages.
-    foreach ($standard_languages as $langcode => $language_names) {
-      $select_options[$langcode] = $language_names[1];
-      $browser_options[$langcode] = new Language(array(
-        'langcode' => $langcode,
-      ));
+    else {
+      // If the language was not found in standard.inc, display its langcode.
+      $select_options[$file->langcode] = $file->langcode;
     }
+    // Build a list of languages simulated for browser detection.
+    $languages[$file->langcode] = new Language(array(
+      'langcode' => $file->langcode,
+    ));
   }
 
-  $browser_langcode = language_from_browser($browser_options);
+  $browser_langcode = language_from_browser($languages);
   $form['langcode'] = array(
     '#type' => 'select',
     '#options' => $select_options,
@@ -1401,10 +1429,9 @@ function install_select_language_form($form, &$form_state, $files = array()) {
     '#default_value' => !empty($browser_langcode) ? $browser_langcode : 'en',
   );
 
-  if (empty($files)) {
+  if (count($files) == 1) {
     $form['help'] = array(
-      '#markup' => '<p>Translations will be downloaded from the <a href="http://localize.drupal.org">Drupal Translation website</a>. ' .
-                   'If you do not want this, select <em>English</em> and continue the installation. For more information, see the <a href="http://drupal.org/documentation/install">online handbook</a>.</p>',
+      '#markup' => '<p><a href="' . check_url(drupal_current_script_url(array('translate' => 'true'))) . '">' . st('Learn how to install Drupal in other languages') . '</a></p>',
     );
   }
   $form['actions'] = array('#type' => 'actions');
@@ -1416,112 +1443,6 @@ function install_select_language_form($form, &$form_state, $files = array()) {
 }
 
 /**
- * Download a translation file for the selected langaguage.
- *
- * @param array $install_state
- *   An array of information about the current installation state.
- *
- * @return string
- *   A themed status report, or an exception if there are requirement errors.
- *   Upon successfull download the page is reloaded and no output is returned.
- */
-function install_download_translation(&$install_state) {
-  // Check whether all conditions are met to download. Download the translation
-  // if possible.
-  $requirements = install_check_translations($install_state);
-  if ($output = install_display_requirements($install_state, $requirements)) {
-    return $output;
-  }
-
-  // The download was successfull, reload the page in the new lanagage.
-  install_goto(install_redirect_url($install_state));
-}
-
-/**
- * Attempts to get a file using drupal_http_request and to store it locally.
- *
- * @param string $uri
- *   The URI of the file to grab.
- * @param string $destination
- *   Stream wrapper URI specifying where the file should be placed. If a
- *   directory path is provided, the file is saved into that directory under its
- *   original name. If the path contains a filename as well, that one will be
- *   used instead.
- *
- * @return boolean
- *   TRUE on success, FALSE on failure.
- */
-function install_retrieve_file($uri, $destination) {
-  $parsed_url = parse_url($uri);
-  if (is_dir(drupal_realpath($destination))) {
-    // Prevent URIs with triple slashes when gluing parts together.
-    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
-  }
-  else {
-    $path = $destination;
-  }
-  $result = drupal_http_request($uri);
-  if ($result->code != 200) {
-    return FALSE;
-  }
-  if (file_put_contents($path, $result->data) === FALSE) {
-    return FALSE;
-  }
-  return TRUE;
-}
-
-/**
- *  Checks if the localization server can be contacted.
- *
- * @param string $uri
- *  The URI to contact.
- *
- * @return string
- *   URI of the server if the localization server was contacted successfully.
- *   FALSE if not.
- */
-function install_check_localization_server($uri) {
-  $result = drupal_http_request($uri, array('method' => 'HEAD'));
-  return (!isset($result->error) && $result->code == 200);
-}
-
-/**
- * Gets the core release version for localization.
- *
- * In case core has a development version we fall back to the latest stable
- * release. e.g. 8.2-dev falls back to 8.1. 8.0-dev falls back to 7.0. Fallback
- * is required because the localization server only provides translation files
- * for stable releases.
- *
- * @return array
- *   Associative array containing 'core' and 'version' of the release.
- */
-function install_get_localization_release() {
-  if (strpos(VERSION, 'dev')) {
-    list($version, ) = explode('-', VERSION);
-    list($major, $minor) = explode('.', $version);
-
-    // Calculate the major and minor release numbers to fall back to.
-    // E.g. 8.0-dev falls back to 7.0 and 8.2-dev falls back to 8.1.
-    if ($minor == 0) {
-      $major--;
-    }
-    else {
-      $minor--;
-    }
-    $release = "$major.$minor";
-  }
-  else {
-    $release = VERSION;
-  }
-
-  return array(
-    'core' => "$major.x",
-    'version' => $release,
-  );
-}
-
-/**
  * Indicates that there are no profiles available.
  */
 function install_no_profile_error() {
@@ -1640,10 +1561,10 @@ function install_profile_modules(&$install_state) {
  *   The batch definition, if there are language files to import.
  */
 function install_import_translations(&$install_state) {
-  include_once DRUPAL_ROOT . '/core/modules/locale/locale.bulk.inc';
-  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
-
+  include_once drupal_get_path('module', 'locale') . '/locale.bulk.inc';
   $langcode = $install_state['parameters']['langcode'];
+
+  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
   $standard_languages = standard_language_list();
   if (!isset($standard_languages[$langcode])) {
     // Drupal does not know about this language, so we prefill its values with
@@ -1664,39 +1585,16 @@ function install_import_translations(&$install_state) {
     language_save($language);
   }
 
-  // If a non-English language was selected, remove English and import the
-  // translations.
+  // If a non-english language was selected, remove English.
   if ($langcode != 'en') {
     language_delete('en');
-
-    // Set up a batch to import translations for the newly added language.
-    _install_prepare_import();
-    module_load_include('fetch.inc', 'locale');
-    if ($batch = locale_translation_batch_fetch_build(array(), array($langcode))) {
-      return $batch;
-    }
   }
-}
-
-/**
- * Tells the translation import process that Drupal core is installed.
- */
-function _install_prepare_import() {
-  global $install_state;
 
-  $release = install_get_localization_release();
-  db_insert('locale_project')
-    ->fields(array(
-      'name' => 'drupal',
-      'project_type' => 'module',
-      'core' => $release['core'],
-      'version' => $release['version'],
-      'server_pattern' => $install_state['server_pattern'],
-      'status' => 1,
-    ))
-    ->execute();
-  module_load_include('compare.inc', 'locale');
-  locale_translation_check_projects_local(array('drupal'), array($install_state['parameters']['langcode']));
+  // Collect files to import for this language.
+  $batch = locale_translate_batch_import_files(array('langcode' => $langcode));
+  if (!empty($batch)) {
+    return $batch;
+  }
 }
 
 /**
@@ -1749,29 +1647,20 @@ function install_configure_form($form, &$form_state, &$install_state) {
 /**
  * Finishes importing files at end of installation.
  *
- * If other projects besides Drupal core have been installed, their translation
- * will be imported here.
- *
  * @param $install_state
  *   An array of information about the current installation state.
  *
  * @return
  *   The batch definition, if there are language files to import.
+ *
+ * @todo
+ *   This currently does the same as the first import step. Need to revisit
+ *   once we have l10n_update functionality integrated. See
+ *   http://drupal.org/node/1191488.
  */
 function install_import_translations_remaining(&$install_state) {
-  module_load_include('fetch.inc', 'locale');
-  module_load_include('compare.inc', 'locale');
-
-  // Build a fresh list of installed projects. When more projects than core are
-  // installed, their translations will be downloaded (if required) and imported
-  // using a batch.
-  $projects = locale_translation_build_projects();
-  if (count($projects) > 1) {
-    $options = _locale_translation_default_update_options();
-    if ($batch =  locale_translation_batch_update_build(array(), array($install_state['parameters']['langcode']), $options)) {
-      return $batch;
-    }
-  }
+  include_once drupal_get_path('module', 'locale') . '/locale.bulk.inc';
+  return locale_translate_batch_import_files(array('langcode' => $install_state['parameters']['langcode']));
 }
 
 /**
@@ -1835,162 +1724,6 @@ function _install_profile_modules_finished($success, $results, $operations) {
 /**
  * Checks installation requirements and reports any errors.
  */
-function install_check_translations($install_state) {
-  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
-  $requirements = array();
-
-  $readable = FALSE;
-  $writable = FALSE;
-  $executable = FALSE;
-  $files_directory = variable_get('file_public_path', conf_path() . '/files');
-  $translations_directory = variable_get('locale_translate_file_directory', conf_path() . '/files/translations');
-  $translations_directory_exists = FALSE;
-  $online = FALSE;
-  $server_available = FALSE;
-  $translation_available = FALSE;
-
-  // First attempt to create or make writable the files directory.
-  file_prepare_directory($files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
-  // Then, attempt to create or make writable the translations directory.
-  file_prepare_directory($translations_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
-
-  // Get values so the requirements errors can be specific.
-  if (drupal_verify_install_file($translations_directory, FILE_EXIST|FILE_WRITABLE, 'dir')) {
-    $readable = is_readable($translations_directory);
-    $writable = is_writable($translations_directory);
-    $executable = is_executable($translations_directory);
-    $translations_directory_exists = TRUE;
-  }
-
-  // Build URLs for the translation file and the translation server.
-  $release = install_get_localization_release();
-  $langcode = $install_state['parameters']['langcode'];
-  $variables = array(
-    '%project' => 'drupal',
-    '%version' => $release['version'],
-    '%core' => $release['core'],
-    '%language' => $langcode,
-  );
-  $translation_url = strtr($install_state['server_pattern'], $variables);
-  $elements = parse_url($translation_url);
-  $server_url = $elements['scheme'] . '://' . $elements['host'];
-
-  // Build the language name for display.
-  $languages = standard_language_list();
-  $language = isset($languages[$langcode]) ? $languages[$langcode][0] : $langcode;
-
-  // Check if the desirered translation file is available and if the translation
-  // server can be reached, or in other words if we have an internet connection.
-  if ($translation_available = install_check_localization_server($translation_url)) {
-    $online = TRUE;
-    $server_available = TRUE;
-  }
-  else {
-    if ($server_available = install_check_localization_server($server_url)) {
-      $online = TRUE;
-    }
-  }
-
-  // If the translations directory does not exists, throw an error.
-  if (!$translations_directory_exists) {
-    $requirements['translations directory exists'] = array(
-      'title'       => st('Translations directory'),
-      'value'       => st('The translations directory does not exist.'),
-      'severity'    => REQUIREMENT_ERROR,
-      'description' => st('The installer requires that you create a translations directory as part of the installation process. Create the directory %translations_directory . More details about installing Drupal are available in <a href="@install_txt">INSTALL.txt</a>.', array('%translations_directory' => $translations_directory, '@install_txt' => base_path() . 'core/INSTALL.txt')),
-    );
-  }
-  else {
-    $requirements['translations directory exists'] = array(
-      'title'       => st('Translations directory'),
-      'value'       => st('The diretory %translations_directory exists.', array('%translations_directory' => $translations_directory)),
-    );
-    // If the translations directory is not readable, throw an error.
-    if (!$readable) {
-      $requirements['translations directory readable'] = array(
-      'title'       => st('Translations directory'),
-        'value'       => st('The translations directory is not readable.'),
-        'severity'    => REQUIREMENT_ERROR,
-        'description' => st('The installer requires read permissions to %translations_directory at all times. If you are unsure how to grant file permissions, consult the <a href="@handbook_url">online handbook</a>.', array('%translations_directory' => $translations_directory, '@handbook_url' => 'http://drupal.org/server-permissions')),
-      );
-    }
-    // If translations directory is not writable, throw an error.
-    if (!$writable) {
-      $requirements['translations directory writable'] = array(
-      'title'       => st('Translations directory'),
-        'value'       => st('The translations directory is not writable.'),
-        'severity'    => REQUIREMENT_ERROR,
-        'description' => st('The installer requires write permissions to %translations_directory during the installation process. If you are unsure how to grant file permissions, consult the <a href="@handbook_url">online handbook</a>.', array('%translations_directory' => $translations_directory, '@handbook_url' => 'http://drupal.org/server-permissions')),
-      );
-    }
-    else {
-      $requirements['translations directory writable'] = array(
-      'title'       => st('Translations directory'),
-        'value'       => st('The translations directory is writable.'),
-      );
-    }
-    // If translations directory is not executable, throw an error.
-    if (!$executable) {
-      $requirements['translations directory executable'] = array(
-      'title'       => st('Translations directory'),
-        'value'       => st('The translations directory is not executable.'),
-        'severity'    => REQUIREMENT_ERROR,
-        'description' => st('The installer requires execute permissions to %translations_directory during the installation process. If you are unsure how to grant file permissions, consult the <a href="@handbook_url">online handbook</a>.', array('%translations_directory' => $translations_directory, '@handbook_url' => 'http://drupal.org/server-permissions')),
-      );
-    }
-  }
-
-  // If the translations server can not be contacted, throw an error.
-  if (!$online) {
-    $requirements['online'] = array(
-      'title'       => st('Internet'),
-      'value'       => st('The translation server is offline.'),
-      'severity'    => REQUIREMENT_ERROR,
-      'description' => st('The installer requires to contact the translation server to download a translation file. Check your internet connection and verify that your website can reach the translation server at <a href="!server_url">!server_url</a>.', array('!server_url' => $server_url)),
-    );
-  }
-  else {
-    $requirements['online'] = array(
-      'title'       => st('Internet'),
-      'value'       => st('The translation server is online.'),
-    );
-    // If translation file is not found at the translation server, throw an
-    // error.
-    if (!$translation_available) {
-      $requirements['translation available'] = array(
-      'title'       => st('Translation'),
-        'value'       => st('The %language translation is not available.', array('%language' => $language)),
-        'severity'    => REQUIREMENT_ERROR,
-        'description' => st('The %language translation file is not available at the translation server. <a href="!url">Choose a different language</a> or select English and translate your website later.', array('%language' => $language, '!url' => check_url($_SERVER['SCRIPT_NAME']))),
-      );
-    }
-    else {
-      $requirements['translation available'] = array(
-      'title'       => st('Translation'),
-        'value'       => st('The %language translation is available.', array('%language' => $language)),
-      );
-    }
-  }
-
-  if ($translations_directory_exists && $readable && $writable && $executable && $translation_available) {
-    $translation_downloaded = install_retrieve_file($translation_url, $translations_directory);
-
-    if (!$translation_downloaded) {
-      $requirements['translation downloaded'] = array(
-      'title'       => st('Translation'),
-        'value'       => st('The %language translation could not be downloaded.', array('%language' => $language)),
-        'severity'    => REQUIREMENT_ERROR,
-        'description' => st('The %language translation file could not be downloaded. <a href="!url">Choose a different language</a> or select English and translate your website later.', array('%language' => $language, '!url' => check_url($_SERVER['SCRIPT_NAME']))),
-      );
-    }
-  }
-
-  return $requirements;
-}
-
-/**
- * Checks installation requirements and reports any errors.
- */
 function install_check_requirements($install_state) {
   $profile = $install_state['parameters']['profile'];
 
@@ -2126,56 +1859,6 @@ function install_check_requirements($install_state) {
 }
 
 /**
- * Displays installation requirements.
- *
- * @param array $install_state
- *   An array of information about the current installation state.
- * @param array $requirements
- *   An array of requirements, in the same format as is returned by
- *   hook_requirements().
- *
- * @return
- *   A themed status report, or an exception if there are requirement errors.
- *   If there are only requirement warnings, a themed status report is shown
- *   initially, but the user is allowed to bypass it by providing 'continue=1'
- *   in the URL. Otherwise, no output is returned, so that the next task can be
- *   run in the same page request.
- *
- * @thows \Exception
- */
-function install_display_requirements($install_state, $requirements) {
-  // Check the severity of the requirements reported.
-  $severity = drupal_requirements_severity($requirements);
-
-  // If there are errors, always display them. If there are only warnings, skip
-  // them if the user has provided a URL parameter acknowledging the warnings
-  // and indicating a desire to continue anyway. See drupal_requirements_url().
-  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
-    if ($install_state['interactive']) {
-      drupal_set_title(st('Requirements problem'));
-      $status_report = theme('status_report', array('requirements' => $requirements));
-      $status_report .= st('Check the messages and <a href="!url">try again</a>.', array('!url' => check_url(drupal_requirements_url($severity))));
-      return $status_report;
-    }
-    else {
-      // Throw an exception showing any unmet requirements.
-      $failures = array();
-      foreach ($requirements as $requirement) {
-        // Skip warnings altogether for non-interactive installations; these
-        // proceed in a single request so there is no good opportunity (and no
-        // good method) to warn the user anyway.
-        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
-          $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
-        }
-      }
-      if (!empty($failures)) {
-        throw new \Exception(implode("\n\n", $failures));
-      }
-    }
-  }
-}
-
-/**
  * Form constructor for a site configuration form.
  *
  * @param $install_state
diff --git a/core/includes/install.inc b/core/includes/install.inc
index 9223b9c..aada754 100644
--- a/core/includes/install.inc
+++ b/core/includes/install.inc
@@ -429,10 +429,6 @@ function drupal_install_system() {
   module_list_reset();
   module_implements_reset();
 
-  // To ensure that the system module can be found by the plugin system, warm
-  // the module list cache.
-  // @todo Remove this in http://drupal.org/node/1798732.
-  module_list();
   config_install_default_config('module', 'system');
 
   module_invoke('system', 'install');
diff --git a/core/includes/menu.inc b/core/includes/menu.inc
index e6810b8..7d419ac 100644
--- a/core/includes/menu.inc
+++ b/core/includes/menu.inc
@@ -2641,6 +2641,7 @@ function menu_reset_static_cache() {
   drupal_static_reset('menu_tree');
   drupal_static_reset('menu_tree_all_data');
   drupal_static_reset('menu_tree_page_data');
+  drupal_static_reset('menu_load_all');
   drupal_static_reset('menu_link_get_preferred');
 }
 
diff --git a/core/includes/path.inc b/core/includes/path.inc
index d0c954e..ba7c034 100644
--- a/core/includes/path.inc
+++ b/core/includes/path.inc
@@ -96,7 +96,7 @@ function current_path() {
 }
 
 /**
- * Fetches a specific URL alias from the database.
+ * Fetch a specific URL alias from the database.
  *
  * @param $conditions
  *   A string representing the source, a number representing the pid, or an
@@ -118,11 +118,11 @@ function path_load($conditions) {
 }
 
 /**
- * Determines whether a path is in the administrative section of the site.
+ * Determine whether a path is in the administrative section of the site.
  *
- * By default, paths are considered to be non-administrative. If a path does
- * not match any of the patterns in path_get_admin_paths(), or if it matches
- * both administrative and non-administrative patterns, it is considered
+ * By default, paths are considered to be non-administrative. If a path does not
+ * match any of the patterns in path_get_admin_paths(), or if it matches both
+ * administrative and non-administrative patterns, it is considered
  * non-administrative.
  *
  * @param $path
@@ -146,7 +146,7 @@ function path_is_admin($path) {
 }
 
 /**
- * Gets a list of administrative and non-administrative paths.
+ * Get a list of administrative and non-administrative paths.
  *
  * @return array
  *   An associative array containing the following keys:
diff --git a/core/includes/schema.inc b/core/includes/schema.inc
index b370145..7661dcb 100644
--- a/core/includes/schema.inc
+++ b/core/includes/schema.inc
@@ -123,8 +123,8 @@ function drupal_get_complete_schema($rebuild = FALSE) {
  *   A module name.
  *
  * @return array|bool
- *   If the module has updates, an array of available updates sorted by
- *   version. Otherwise, FALSE.
+ *   If the module has updates, an array of available updates sorted by version.
+ *   Otherwise, FALSE.
  */
 function drupal_get_schema_versions($module) {
   $updates = &drupal_static(__FUNCTION__, NULL);
@@ -369,9 +369,9 @@ function drupal_schema_fields_sql($table, $prefix = NULL) {
  *   An object or array representing the record to write, passed in by
  *   reference. If inserting a new record, values not provided in $record will
  *   be populated in $record and in the database with the default values from
- *   the schema, as well as a single serial (auto-increment) field
- *   (if present). If updating an existing record, only provided values are
- *   updated in the database, and $record is not modified.
+ *   the schema, as well as a single serial (auto-increment) field (if present).
+ *   If updating an existing record, only provided values are updated in the
+ *   database, and $record is not modified.
  * @param array $primary_keys
  *   To indicate that this is a new record to be inserted, omit this argument.
  *   If this is an update, this argument specifies the primary keys' field
diff --git a/core/includes/session.inc b/core/includes/session.inc
index 31e67a6..9ffd3d1 100644
--- a/core/includes/session.inc
+++ b/core/includes/session.inc
@@ -270,7 +270,7 @@ function drupal_session_initialize() {
 }
 
 /**
- * Starts a session forcefully, preserving already set session data.
+ * Forcefully starts a session, preserving already set session data.
  *
  * @ingroup php_wrappers
  */
diff --git a/core/includes/tablesort.inc b/core/includes/tablesort.inc
index c42b1f4..818b61d 100644
--- a/core/includes/tablesort.inc
+++ b/core/includes/tablesort.inc
@@ -13,7 +13,7 @@
  */
 
 /**
- * Initializes the table sort context.
+ * Initialize the table sort context.
  */
 function tablesort_init($header) {
   $ts = tablesort_get_order($header);
@@ -23,7 +23,7 @@ function tablesort_init($header) {
 }
 
 /**
- * Formats a column header.
+ * Format a column header.
  *
  * If the cell in question is the column header for the current sort criterion,
  * it gets special formatting. All possible sort criteria become links.
@@ -34,7 +34,6 @@ function tablesort_init($header) {
  *   An array of column headers in the format described in theme_table().
  * @param $ts
  *   The current table sort context as returned from tablesort_init().
- *
  * @return
  *   A properly formatted cell, ready for _theme_table_cell().
  */
@@ -64,7 +63,7 @@ function tablesort_header($cell, $header, $ts) {
 }
 
 /**
- * Formats a table cell.
+ * Format a table cell.
  *
  * Adds a class attribute to all cells in the currently active column.
  *
@@ -76,7 +75,6 @@ function tablesort_header($cell, $header, $ts) {
  *   The current table sort context as returned from tablesort_init().
  * @param $i
  *   The index of the cell's table column.
- *
  * @return
  *   A properly formatted cell, ready for _theme_table_cell().
  */
@@ -93,7 +91,7 @@ function tablesort_cell($cell, $header, $ts, $i) {
 }
 
 /**
- * Composes a URL query parameter array for table sorting links.
+ * Compose a URL query parameter array for table sorting links.
  *
  * @return
  *   A URL query parameter array that consists of all components of the current
@@ -104,11 +102,10 @@ function tablesort_get_query_parameters() {
 }
 
 /**
- * Determines the current sort criterion.
+ * Determine the current sort criterion.
  *
  * @param $headers
  *   An array of column headers in the format described in theme_table().
- *
  * @return
  *   An associative array describing the criterion, containing the keys:
  *   - "name": The localized title of the table column.
@@ -141,11 +138,10 @@ function tablesort_get_order($headers) {
 }
 
 /**
- * Determines the current sort direction.
+ * Determine the current sort direction.
  *
  * @param $headers
  *   An array of column headers in the format described in theme_table().
- *
  * @return
  *   The current sort direction ("asc" or "desc").
  */
diff --git a/core/includes/theme.inc b/core/includes/theme.inc
index bab2af5..9b50f90 100644
--- a/core/includes/theme.inc
+++ b/core/includes/theme.inc
@@ -75,7 +75,7 @@ function drupal_theme_access($theme) {
 }
 
 /**
- * Initializes the theme system by loading the theme.
+ * Initialize the theme system by loading the theme.
  */
 function drupal_theme_initialize() {
   global $theme, $user, $theme_key;
@@ -114,9 +114,8 @@ function drupal_theme_initialize() {
 }
 
 /**
- * Initializes the theme system given already loaded information.
- *
- * This function is useful to initialize a theme when no database is present.
+ * Initialize the theme system given already loaded information. This
+ * function is useful to initialize a theme when no database is present.
  *
  * @param $theme
  *   An object with the following information:
@@ -278,7 +277,7 @@ function _drupal_theme_initialize($theme, $base_theme = array(), $registry_callb
 }
 
 /**
- * Gets the theme registry.
+ * Get the theme registry.
  *
  * @param bool $complete
  *   Optional boolean to indicate whether to return the complete theme registry
@@ -323,7 +322,7 @@ function theme_get_registry($complete = TRUE) {
 }
 
 /**
- * Sets the callback that will be used by theme_get_registry().
+ * Set the callback that will be used by theme_get_registry() to fetch the registry.
  *
  * @param $callback
  *   The name of the callback function.
@@ -339,7 +338,7 @@ function _theme_registry_callback($callback = NULL, array $arguments = array())
 }
 
 /**
- * Gets the theme_registry cache; if it doesn't exist, builds it.
+ * Get the theme_registry cache; if it doesn't exist, build it.
  *
  * @param $theme
  *   The loaded $theme object as returned by list_themes().
@@ -380,17 +379,16 @@ function _theme_load_registry($theme, $base_theme = NULL, $theme_engine = NULL,
 }
 
 /**
- * Writes the theme_registry cache into the database.
+ * Write the theme_registry cache into the database.
  */
 function _theme_save_registry($theme, $registry) {
   cache()->set("theme_registry:$theme->name", $registry, CacheBackendInterface::CACHE_PERMANENT, array('theme_registry' => TRUE));
 }
 
 /**
- * Forces the system to rebuild the theme registry.
- *
- * This function should be called when modules are added to the system, or when
- * a dynamic system needs to add more theme hooks.
+ * Force the system to rebuild the theme registry; this should be called
+ * when modules are added to the system, or when a dynamic system needs
+ * to add more theme hooks.
  */
 function drupal_theme_rebuild() {
   drupal_static_reset('theme_get_registry');
@@ -407,17 +405,17 @@ function drupal_theme_rebuild() {
  *   - 'type': The passed-in $type.
  *   - 'theme path': The passed-in $path.
  *   - 'function': The name of the function generating output for this theme
- *     hook. Either defined explicitly in hook_theme() or, if neither
- *     'function' nor 'template' is defined, then the default theme function
- *     name is used. The default theme function name is the theme hook prefixed
- *     by either 'theme_' for modules or '$name_' for everything else. If
- *     'function' is defined, 'template' is not used.
+ *     hook. Either defined explicitly in hook_theme() or, if neither 'function'
+ *     nor 'template' is defined, then the default theme function name is used.
+ *     The default theme function name is the theme hook prefixed by either
+ *     'theme_' for modules or '$name_' for everything else. If 'function' is
+ *     defined, 'template' is not used.
  *   - 'template': The filename of the template generating output for this
  *     theme hook. The template is in the directory defined by the 'path' key of
  *     hook_theme() or defaults to "$path/templates".
  *   - 'variables': The variables for this theme hook as defined in
- *     hook_theme(). If there is more than one implementation and 'variables'
- *     is not specified in a later one, then the previous definition is kept.
+ *     hook_theme(). If there is more than one implementation and 'variables' is
+ *     not specified in a later one, then the previous definition is kept.
  *   - 'render element': The renderable element for this theme hook as defined
  *     in hook_theme(). If there is more than one implementation and
  *     'render element' is not specified in a later one, then the previous
@@ -592,8 +590,7 @@ function _theme_process_registry(&$cache, $name, $type, $theme, $path) {
     $cache = $result + $cache;
   }
 
-  // Let themes have variable processors even if they didn't register a
-  // template.
+  // Let themes have variable processors even if they didn't register a template.
   if ($type == 'theme' || $type == 'base_theme') {
     foreach ($cache as $hook => $info) {
       // Check only if not registered by the theme or engine.
@@ -620,7 +617,7 @@ function _theme_process_registry(&$cache, $name, $type, $theme, $path) {
 }
 
 /**
- * Builds the theme registry cache.
+ * Build the theme registry cache.
  *
  * @param $theme
  *   The loaded $theme object as returned by list_themes().
@@ -682,7 +679,7 @@ function _theme_build_registry($theme, $base_theme, $theme_engine) {
 }
 
 /**
- * Returns a list of all currently available themes.
+ * Return a list of all currently available themes.
  *
  * Retrieved from the database, if available and the site is not in maintenance
  * mode; otherwise compiled freshly from the filesystem.
@@ -861,15 +858,15 @@ function drupal_find_base_themes($themes, $key, $used_keys = array()) {
  * executed (if they exist), in the following order (note that in the following
  * list, HOOK indicates the theme hook name, MODULE indicates a module name,
  * THEME indicates a theme name, and ENGINE indicates a theme engine name):
- * - template_preprocess(&$variables, $hook): Creates a default set of
- *   variables for all theme hooks with template implementations.
+ * - template_preprocess(&$variables, $hook): Creates a default set of variables
+ *   for all theme hooks with template implementations.
  * - template_preprocess_HOOK(&$variables): Should be implemented by the module
  *   that registers the theme hook, to set up default variables.
  * - MODULE_preprocess(&$variables, $hook): hook_preprocess() is invoked on all
  *   implementing modules.
  * - MODULE_preprocess_HOOK(&$variables): hook_preprocess_HOOK() is invoked on
- *   all implementing modules, so that modules that didn't define the theme
- *   hook can alter the variables.
+ *   all implementing modules, so that modules that didn't define the theme hook
+ *   can alter the variables.
  * - ENGINE_engine_preprocess(&$variables, $hook): Allows the theme engine to
  *   set necessary variables for all theme hooks with template implementations.
  * - ENGINE_engine_preprocess_HOOK(&$variables): Allows the theme engine to set
@@ -924,10 +921,10 @@ function drupal_find_base_themes($themes, $key, $used_keys = array()) {
  * @param $hook
  *   The name of the theme hook to call. If the name contains a
  *   double-underscore ('__') and there isn't an implementation for the full
- *   name, the part before the '__' is checked. This allows a fallback to a
- *   more generic implementation. For example, if theme('links__node', ...) is
- *   called, but there is no implementation of that theme hook, then the
- *   'links' implementation is used. This process is iterative, so if
+ *   name, the part before the '__' is checked. This allows a fallback to a more
+ *   generic implementation. For example, if theme('links__node', ...) is
+ *   called, but there is no implementation of that theme hook, then the 'links'
+ *   implementation is used. This process is iterative, so if
  *   theme('links__contextual__node', ...) is called, theme() checks for the
  *   following implementations, and uses the first one that exists:
  *   - links__contextual__node
@@ -1006,8 +1003,7 @@ function theme($hook, $variables = array()) {
   // point path_to_theme() to the currently used theme path:
   $theme_path = $info['theme path'];
 
-  // Include a file if the theme function or variable processor is held
-  // elsewhere.
+  // Include a file if the theme function or variable processor is held elsewhere.
   if (!empty($info['includes'])) {
     foreach ($info['includes'] as $include_file) {
       include_once DRUPAL_ROOT . '/' . $include_file;
@@ -1171,14 +1167,14 @@ function theme($hook, $variables = array()) {
 }
 
 /**
- * Returns the path to the current themed element.
- *
- * It can point to the active theme or the module handling a themed
- * implementation. For example, when invoked within the scope of a theming call
- * it will depend on where the theming function is handled. If implemented from
- * a module, it will point to the module. If implemented from the active theme,
- * it will point to the active theme. When called outside the scope of a
- * theming call, it will always point to the active theme.
+ * Return the path to the current themed element.
+ *
+ * It can point to the active theme or the module handling a themed implementation.
+ * For example, when invoked within the scope of a theming call it will depend
+ * on where the theming function is handled. If implemented from a module, it
+ * will point to the module. If implemented from the active theme, it will point
+ * to the active theme. When called outside the scope of a theming call, it will
+ * always point to the active theme.
  */
 function path_to_theme() {
   global $theme_path;
@@ -1191,7 +1187,7 @@ function path_to_theme() {
 }
 
 /**
- * Allows themes and/or theme engines to discover overridden theme functions.
+ * Allow themes and/or theme engines to easily discover overridden theme functions.
  *
  * @param $cache
  *   The existing cache of theme hooks to test against.
@@ -1248,7 +1244,7 @@ function drupal_find_theme_functions($cache, $prefixes) {
 }
 
 /**
- * Allows themes and/or theme engines to easily discover overridden templates.
+ * Allow themes and/or theme engines to easily discover overridden templates.
  *
  * @param $cache
  *   The existing cache of theme hooks to test against.
@@ -1345,8 +1341,7 @@ function drupal_find_theme_templates($cache, $extension, $path) {
           if (($pos = strpos($match, '.')) !== FALSE) {
             $file = substr($match, 0, $pos);
           }
-          // Put the underscores back in for the hook name and register this
-          // pattern.
+          // Put the underscores back in for the hook name and register this pattern.
           $arg_name = isset($info['variables']) ? 'variables' : 'render element';
           $implementations[strtr($file, '-', '_')] = array(
             'template' => $file,
@@ -1362,7 +1357,7 @@ function drupal_find_theme_templates($cache, $extension, $path) {
 }
 
 /**
- * Retrieves a setting for the current theme or for a given theme.
+ * Retrieve a setting for the current theme or for a given theme.
  *
  * The final setting is obtained from the last value found in the following
  * sources:
@@ -1480,7 +1475,7 @@ function theme_get_setting($setting_name, $theme = NULL) {
 }
 
 /**
- * Renders a system default template, which is essentially a PHP template.
+ * Render a system default template, which is essentially a PHP template.
  *
  * @param $template_file
  *   The filename of the template to render.
@@ -1491,21 +1486,14 @@ function theme_get_setting($setting_name, $theme = NULL) {
  *   The output generated by the template.
  */
 function theme_render_template($template_file, $variables) {
-  // Extract the variables to a local namespace
-  extract($variables, EXTR_SKIP);
-
-  // Start output buffering
-  ob_start();
-
-  // Include the template file
-  include DRUPAL_ROOT . '/' . $template_file;
-
-  // End buffering and return its contents
-  return ob_get_clean();
+  extract($variables, EXTR_SKIP);               // Extract the variables to a local namespace
+  ob_start();                                   // Start output buffering
+  include DRUPAL_ROOT . '/' . $template_file;   // Include the template file
+  return ob_get_clean();                        // End buffering and return its contents
 }
 
 /**
- * Enables a given list of themes.
+ * Enable a given list of themes.
  *
  * @param $theme_list
  *   An array of theme names.
@@ -1533,7 +1521,7 @@ function theme_enable($theme_list) {
 }
 
 /**
- * Disables a given list of themes.
+ * Disable a given list of themes.
  *
  * @param $theme_list
  *   An array of theme names.
@@ -1602,21 +1590,20 @@ function template_preprocess_datetime(&$variables) {
  *
  * @param $variables
  *   An associative array containing:
- *   - timestamp: (optional) A UNIX timestamp for the datetime attribute. If
- *     the datetime cannot be represented as a UNIX timestamp, use a valid
- *     datetime attribute value in $variables['attributes']['datetime'].
+ *   - timestamp: (optional) A UNIX timestamp for the datetime attribute. If the
+ *     datetime cannot be represented as a UNIX timestamp, use a valid datetime
+ *     attribute value in $variables['attributes']['datetime'].
  *   - text: (optional) The content to display within the <time> element. Set
  *     'html' to TRUE if this value is already sanitized for output in HTML.
- *     Defaults to a human-readable representation of the timestamp value or
- *     the datetime attribute value using format_date().
+ *     Defaults to a human-readable representation of the timestamp value or the
+ *     datetime attribute value using format_date().
  *     When invoked as #theme or #theme_wrappers of a render element, the
  *     rendered #children are autoamtically taken over as 'text', unless #text
  *     is explicitly set.
  *   - attributes: (optional) An associative array of HTML attributes to apply
- *     to the <time> element. A datetime attribute in 'attributes' overrides
- *     the 'timestamp'. To create a valid datetime attribute value from a UNIX
- *     timestamp, use format_date() with one of the predefined 'html_*'
- *     formats.
+ *     to the <time> element. A datetime attribute in 'attributes' overrides the
+ *     'timestamp'. To create a valid datetime attribute value from a UNIX
+ *     timestamp, use format_date() with one of the predefined 'html_*' formats.
  *   - html: (optional) Whether 'text' is HTML markup (TRUE) or plain-text
  *     (FALSE). Defaults to FALSE. For example, to use a SPAN tag within the
  *     TIME element, this must be set to TRUE, or the SPAN tag will be escaped.
@@ -1682,13 +1669,13 @@ function theme_status_messages($variables) {
  * theme('link') for rendering the anchor tag.
  *
  * To optimize performance for sites that don't need custom theming of links,
- * the l() function includes an inline copy of this function, and uses that
- * copy if none of the enabled modules or the active theme implement any
- * preprocess or process functions or override this theme implementation.
+ * the l() function includes an inline copy of this function, and uses that copy
+ * if none of the enabled modules or the active theme implement any preprocess
+ * or process functions or override this theme implementation.
  *
  * @param $variables
- *   An associative array containing the keys 'text', 'path', and 'options'.
- *   See the l() function for information about these variables.
+ *   An associative array containing the keys 'text', 'path', and 'options'. See
+ *   the l() function for information about these variables.
  *
  * @see l()
  */
@@ -1709,16 +1696,15 @@ function theme_link($variables) {
  *       item in the links list.
  *     - html: (optional) Whether or not 'title' is HTML. If set, the title
  *       will not be passed through check_plain().
- *     - attributes: (optional) Attributes for the anchor, or for the <span>
- *       tag used in its place if no 'href' is supplied. If element 'class' is
+ *     - attributes: (optional) Attributes for the anchor, or for the <span> tag
+ *       used in its place if no 'href' is supplied. If element 'class' is
  *       included, it must be an array of one or more class names.
- *     If the 'href' element is supplied, the entire link array is passed to
- *     l() as its $options parameter.
+ *     If the 'href' element is supplied, the entire link array is passed to l()
+ *     as its $options parameter.
  *   - attributes: A keyed array of attributes for the UL containing the
  *     list of links.
- *   - heading: (optional) A heading to precede the links. May be an
- *     associative array or a string. If it's an array, it can have the
- *     following elements:
+ *   - heading: (optional) A heading to precede the links. May be an associative
+ *     array or a string. If it's an array, it can have the following elements:
  *     - text: The heading text.
  *     - level: The heading level (e.g. 'h2', 'h3').
  *     - class: (optional) An array of the CSS classes for the heading.
@@ -1858,8 +1844,8 @@ function theme_dropbutton_wrapper($variables) {
  *     attribute to be omitted in some cases. Therefore, this variable defaults
  *     to an empty string, but can be set to NULL for the attribute to be
  *     omitted. Usually, neither omission nor an empty string satisfies
- *     accessibility requirements, so it is strongly encouraged for code
- *     calling theme('image') to pass a meaningful value for this variable.
+ *     accessibility requirements, so it is strongly encouraged for code calling
+ *     theme('image') to pass a meaningful value for this variable.
  *     - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
  *     - http://www.w3.org/TR/xhtml1/dtds.html
  *     - http://dev.w3.org/html5/spec/Overview.html#alt
@@ -2254,8 +2240,7 @@ function theme_table($variables) {
  *
  * @param $variables
  *   An associative array containing:
- *   - style: Set to either 'asc' or 'desc', this determines which icon to
- *     show.
+ *   - style: Set to either 'asc' or 'desc', this determines which icon to show.
  */
 function theme_tablesort_indicator($variables) {
   if ($variables['style'] == "asc") {
@@ -2432,8 +2417,7 @@ function theme_feed_icon($variables) {
  *       - script: To load JavaScript.
  *     - #attributes: (optional) An array of HTML attributes to apply to the
  *       tag.
- *     - #value: (optional) A string containing tag content, such as inline
- *       CSS.
+ *     - #value: (optional) A string containing tag content, such as inline CSS.
  *     - #value_prefix: (optional) A string to prepend to #value, e.g. a CDATA
  *       wrapper prefix.
  *     - #value_suffix: (optional) A string to append to #value, e.g. a CDATA
@@ -2610,9 +2594,8 @@ function template_preprocess(&$variables, $hook) {
   global $user;
   static $count = array(), $default_attributes;
 
-  // Track run count for each hook to provide zebra striping. See
-  // "template_preprocess_block()" which provides the same feature specific to
-  // blocks.
+  // Track run count for each hook to provide zebra striping.
+  // See "template_preprocess_block()" which provides the same feature specific to blocks.
   $count[$hook] = isset($count[$hook]) && is_int($count[$hook]) ? $count[$hook] : 1;
   $variables['zebra'] = ($count[$hook] % 2) ? 'odd' : 'even';
   $variables['id'] = $count[$hook]++;
@@ -2933,8 +2916,7 @@ function template_process_html(&$variables) {
  * @return
  *   An array of suggestions, suitable for adding to
  *   $variables['theme_hook_suggestions'] within a preprocess function or to
- *   $variables['attributes']['class'] if the suggestions represent extra CSS
- *   classes.
+ *   $variables['attributes']['class'] if the suggestions represent extra CSS classes.
  */
 function theme_get_suggestions($args, $base, $delimiter = '__') {
 
@@ -2984,13 +2966,13 @@ function theme_get_suggestions($args, $base, $delimiter = '__') {
 }
 
 /**
- * Process variables for maintenance-page.tpl.php.
+ * The variables array generated here is a mirror of template_preprocess_page().
+ * This preprocessor will run its course when theme_maintenance_page() is
+ * invoked.
  *
- * The variables array generated here is a mirror of
- * template_preprocess_page(). This preprocessor will run its course when
- * theme_maintenance_page() is invoked. An alternate template file of
- * maintenance-page--offline.tpl.php can be used when the database is offline to
- * hide errors and completely replace the content.
+ * An alternate template file of "maintenance-page--offline.tpl.php" can be
+ * used when the database is offline to hide errors and completely replace the
+ * content.
  *
  * The $variables array contains the following arguments:
  * - $content
@@ -3087,13 +3069,10 @@ function template_preprocess_maintenance_page(&$variables) {
 }
 
 /**
- * Theme process function for theme_maintenance_field().
- *
  * The variables array generated here is a mirror of template_process_html().
  * This processor will run its course when theme_maintenance_page() is invoked.
  *
  * @see maintenance-page.tpl.php
- * @see template_process_html()
  */
 function template_process_maintenance_page(&$variables) {
   $variables['head']    = drupal_get_html_head();
@@ -3105,7 +3084,7 @@ function template_process_maintenance_page(&$variables) {
 /**
  * Preprocess variables for region.tpl.php
  *
- * Prepares the values passed to the theme_region function to be passed into a
+ * Prepare the values passed to the theme_region function to be passed into a
  * pluggable template engine. Uses the region name to generate a template file
  * suggestions. If none are found, the default region.tpl.php is used.
  *
diff --git a/core/includes/theme.maintenance.inc b/core/includes/theme.maintenance.inc
index ba88661..4aa0a13 100644
--- a/core/includes/theme.maintenance.inc
+++ b/core/includes/theme.maintenance.inc
@@ -10,9 +10,9 @@
  *
  * Used for site installs, updates and when the site is in maintenance mode.
  * It also applies when the database is unavailable or bootstrap was not
- * complete. Seven is always used for the initial install and update
- * operations. In other cases, Bartik is used, but this can be overridden by
- * setting a "maintenance_theme" key in the $conf variable in settings.php.
+ * complete. Seven is always used for the initial install and update operations.
+ * In other cases, Bartik is used, but this can be overridden by setting a
+ * "maintenance_theme" key in the $conf variable in settings.php.
  */
 function _drupal_maintenance_theme() {
   global $theme, $theme_key, $conf;
@@ -89,7 +89,7 @@ function _drupal_maintenance_theme() {
 }
 
 /**
- * Builds the registry when the site needs to bypass any database calls.
+ * This builds the registry when the site needs to bypass any database calls.
  */
 function _theme_load_offline_registry($theme, $base_theme = NULL, $theme_engine = NULL) {
   return _theme_build_registry($theme, $base_theme, $theme_engine);
@@ -165,7 +165,7 @@ function theme_update_page($variables) {
 }
 
 /**
- * Returns HTML for a results report of an operation run by authorize.php.
+ * Returns HTML for a report of the results from an operation run via authorize.php.
  *
  * @param $variables
  *   An associative array containing:
diff --git a/core/includes/token.inc b/core/includes/token.inc
index 5cbb4ee..a6f8064 100644
--- a/core/includes/token.inc
+++ b/core/includes/token.inc
@@ -61,11 +61,10 @@
  *   replacement process. Supported options are:
  *   - langcode: A language code to be used when generating locale-sensitive
  *     tokens.
- *   - callback: A callback function that will be used to post-process the
- *     array of token replacements after they are generated. For example, a
- *     module using tokens in a text-only email might provide a callback to
- *     strip HTML entities from token values before they are inserted into the
- *     final text.
+ *   - callback: A callback function that will be used to post-process the array
+ *     of token replacements after they are generated. For example, a module
+ *     using tokens in a text-only email might provide a callback to strip HTML
+ *     entities from token values before they are inserted into the final text.
  *   - clear: A boolean flag indicating that tokens should be removed from the
  *     final text if no replacement value can be generated.
  *   - sanitize: A boolean flag indicating that tokens should be sanitized for
@@ -191,10 +190,10 @@ function token_generate($type, array $tokens, array $data = array(), array $opti
 }
 
 /**
- * Returns a list of tokens that begin with a specific prefix.
+ * Given a list of tokens, returns those that begin with a specific prefix.
  *
- * Used to extract a group of 'chained' tokens (such as [node:author:name])
- * from the full list of tokens found in text. For example:
+ * Used to extract a group of 'chained' tokens (such as [node:author:name]) from
+ * the full list of tokens found in text. For example:
  * @code
  *   $data = array(
  *     'author:name' => '[node:author:name]',
@@ -231,10 +230,8 @@ function token_find_with_prefix(array $tokens, $prefix, $delimiter = ':') {
 /**
  * Returns metadata describing supported tokens.
  *
- * The metadata array contains token type, name, and description data as well
- * as an optional pointer indicating that the token chains to another set of
- * tokens.
- *
+ * The metadata array contains token type, name, and description data as well as
+ * an optional pointer indicating that the token chains to another set of tokens.
  * For example:
  * @code
  *   $data['types']['node'] = array(
diff --git a/core/includes/unicode.inc b/core/includes/unicode.inc
index 70a8fde..a2ff76b 100644
--- a/core/includes/unicode.inc
+++ b/core/includes/unicode.inc
@@ -1,13 +1,10 @@
 <?php
 
 /**
- * @file
- * Provides Unicode-related conversions and operations.
- */
-
-/**
  * Matches Unicode characters that are word boundaries.
  *
+ * @see http://unicode.org/glossary
+ *
  * Characters with the following General_category (gc) property values are used
  * as word boundaries. While this does not fully conform to the Word Boundaries
  * algorithm described in http://unicode.org/reports/tr29, as PCRE does not
@@ -26,8 +23,6 @@
  * Note that the PCRE property matcher is not used because we wanted to be
  * compatible with Unicode 5.2.0 regardless of the PCRE version used (and any
  * bugs in PCRE property tables).
- *
- * @see http://unicode.org/glossary
  */
 define('PREG_CLASS_UNICODE_WORD_BOUNDARY',
   '\x{0}-\x{2F}\x{3A}-\x{40}\x{5B}-\x{60}\x{7B}-\x{A9}\x{AB}-\x{B1}\x{B4}' .
@@ -67,7 +62,7 @@
   '\x{FF3B}-\x{FF40}\x{FF5B}-\x{FF65}\x{FFE0}-\x{FFFD}');
 
 /**
- * Returns Unicode library status and errors.
+ * Return Unicode library status and errors.
  */
 function unicode_requirements() {
   // Ensure translations don't break during installation.
@@ -118,14 +113,14 @@ function unicode_requirements() {
 }
 
 /**
- * Prepares a new XML parser.
+ * Prepare a new XML parser.
  *
- * This is a wrapper around xml_parser_create() which extracts the encoding
- * from the XML data first and sets the output encoding to UTF-8. This function
- * should be used instead of xml_parser_create(), because PHP 4's XML parser
- * doesn't check the input encoding itself. "Starting from PHP 5, the input
- * encoding is automatically detected, so that the encoding parameter specifies
- * only the output encoding."
+ * This is a wrapper around xml_parser_create() which extracts the encoding from
+ * the XML data first and sets the output encoding to UTF-8. This function should
+ * be used instead of xml_parser_create(), because PHP 4's XML parser doesn't
+ * check the input encoding itself. "Starting from PHP 5, the input encoding is
+ * automatically detected, so that the encoding parameter specifies only the
+ * output encoding."
  *
  * This is also where unsupported encodings will be converted. Callers should
  * take this into account: $data might have been changed after the call.
@@ -174,7 +169,7 @@ function drupal_xml_parser_create(&$data) {
 }
 
 /**
- * Converts data to UTF-8.
+ * Convert data to UTF-8
  *
  * Requires the iconv, GNU recode or mbstring PHP extension.
  *
@@ -205,15 +200,15 @@ function drupal_convert_to_utf8($data, $encoding) {
 }
 
 /**
- * Truncates a UTF-8-encoded string safely to a number of bytes.
+ * Truncate a UTF-8-encoded string safely to a number of bytes.
  *
  * If the end position is in the middle of a UTF-8 sequence, it scans backwards
  * until the beginning of the byte sequence.
  *
  * Use this function whenever you want to chop off a string at an unsure
  * location. On the other hand, if you're sure that you're splitting on a
- * character boundary (e.g. after using strpos() or similar), you can safely
- * use substr() instead.
+ * character boundary (e.g. after using strpos() or similar), you can safely use
+ * substr() instead.
  *
  * @param $string
  *   The string to truncate.
@@ -267,7 +262,7 @@ function drupal_truncate_bytes($string, $len) {
  *   boundaries, giving you "See myverylongurl..." (assuming you had set
  *   $add_ellipses to TRUE).
  *
- * @return string
+ * @return
  *   The truncated string.
  */
 function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
@@ -320,7 +315,8 @@ function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis =
 }
 
 /**
- * Encodes MIME/HTTP header values that contain incorrectly encoded characters.
+ * Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded
+ * characters.
  *
  * For example, mime_header_encode('tést.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".
  *
@@ -332,14 +328,6 @@ function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis =
  *   each chunk starts and ends on a character boundary.
  * - Using \n as the chunk separator may cause problems on some systems and may
  *   have to be changed to \r\n or \r.
- *
- * @param $string
- *   The header to encode.
- *
- * @return string
- *   The mime-encoded header.
- *
- * @see mime_header_decode()
  */
 function mime_header_encode($string) {
   if (preg_match('/[^\x20-\x7E]/', $string)) {
@@ -359,15 +347,7 @@ function mime_header_encode($string) {
 }
 
 /**
- * Decodes MIME/HTTP encoded header values.
- *
- * @param $header
- *   The header to decode.
- *
- * @return string
- *   The mime-decoded header.
- *
- * @see mime_header_encode()
+ * Complement to mime_header_encode
  */
 function mime_header_decode($header) {
   // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
@@ -377,17 +357,7 @@ function mime_header_decode($header) {
 }
 
 /**
- * Decodes encoded header data passed from mime_header_decode().
- *
- * Callback for preg_replace_callback() within mime_header_decode().
- *
- * @param $matches
- *   The array of matches from preg_replace_callback().
- *
- * @return string
- *   The mime-decoded string.
- *
- * @see mime_header_decode()
+ * Helper function to mime_header_decode
  */
 function _mime_header_decode($matches) {
   // Regexp groups:
@@ -404,9 +374,9 @@ function _mime_header_decode($matches) {
 /**
  * Decodes all HTML entities (including numerical ones) to regular UTF-8 bytes.
  *
- * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;"
- * , not "<"). Be careful when using this function, as decode_entities can
- * revert previous sanitization efforts (&lt;script&gt; will become <script>).
+ * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;",
+ * not "<"). Be careful when using this function, as decode_entities can revert
+ * previous sanitization efforts (&lt;script&gt; will become <script>).
  *
  * @param $text
  *   The text to decode entities in.
@@ -419,15 +389,8 @@ function decode_entities($text) {
 }
 
 /**
- * Counts the number of characters in a UTF-8 string.
- *
- * This is less than or equal to the byte count.
- *
- * @param $text
- *   The string to run the operation on.
- *
- * @return integer
- *   The length of the string.
+ * Count the amount of characters in a UTF-8 string. This is less than or
+ * equal to the byte count.
  *
  * @ingroup php_wrappers
  */
@@ -445,12 +408,6 @@ function drupal_strlen($text) {
 /**
  * Uppercase a UTF-8 string.
  *
- * @param $text
- *   The string to run the operation on.
- *
- * @return string
- *   The string in uppercase.
- *
  * @ingroup php_wrappers
  */
 function drupal_strtoupper($text) {
@@ -470,12 +427,6 @@ function drupal_strtoupper($text) {
 /**
  * Lowercase a UTF-8 string.
  *
- * @param $text
- *   The string to run the operation on.
- *
- * @return string
- *   The string in lowercase.
- *
  * @ingroup php_wrappers
  */
 function drupal_strtolower($text) {
@@ -493,28 +444,15 @@ function drupal_strtolower($text) {
 }
 
 /**
- * Flips U+C0-U+DE to U+E0-U+FD and back.
- *
- * @param $matches
- *   An array of matches.
- *
- * @return array
- *   The Latin-1 version of the array of matches.
- *
- * @see drupal_strtolower()
+ * Helper function for case conversion of Latin-1.
+ * Used for flipping U+C0-U+DE to U+E0-U+FD and back.
  */
 function _unicode_caseflip($matches) {
   return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
 }
 
 /**
- * Capitalizes the first letter of a UTF-8 string.
- *
- * @param $text
- *   The string to convert.
- *
- * @return
- *   The string with the first letter as uppercase.
+ * Capitalize the first letter of a UTF-8 string.
  *
  * @ingroup php_wrappers
  */
@@ -524,21 +462,12 @@ function drupal_ucfirst($text) {
 }
 
 /**
- * Cuts off a piece of a string based on character indices and counts.
- *
- * Follows the same behavior as PHP's own substr() function. Note that for
- * cutting off a string at a known character/substring location, the usage of
- * PHP's normal strpos/substr is safe and much faster.
+ * Cut off a piece of a string based on character indices and counts. Follows
+ * the same behavior as PHP's own substr() function.
  *
- * @param $text
- *   The input string.
- * @param $start
- *   The position at which to start reading.
- * @param $length
- *   The number of characters to read.
- *
- * @return
- *   The shortened string.
+ * Note that for cutting off a string at a known character/substring
+ * location, the usage of PHP's normal strpos/substr is safe and
+ * much faster.
  *
  * @ingroup php_wrappers
  */
diff --git a/core/includes/update.inc b/core/includes/update.inc
index fb81b76..4261a9b 100644
--- a/core/includes/update.inc
+++ b/core/includes/update.inc
@@ -47,7 +47,7 @@ function update_fix_compatibility() {
 }
 
 /**
- * Tests the compatibility of a module or theme.
+ * Helper function to test compatibility of a module or theme.
  */
 function update_check_incompatibility($name, $type = 'module') {
   static $themes, $modules;
@@ -418,7 +418,7 @@ function update_prepare_d8_bootstrap() {
 }
 
 /**
- * Fixes stored include paths to match the "/core" migration.
+ * Fix stored include paths to match the "/core" migration.
  */
 function update_prepare_stored_includes() {
   // Update language negotiation settings.
@@ -434,7 +434,7 @@ function update_prepare_stored_includes() {
 }
 
 /**
- * Prepares Drupal 8 language changes for the bootstrap if needed.
+ * Prepare Drupal 8 language changes for the bootstrap if needed.
  */
 function update_prepare_d8_language() {
   if (db_table_exists('languages')) {
@@ -603,7 +603,8 @@ function update_prepare_d8_language() {
 }
 
 /**
- * Performs Drupal 7.x to 8.x required update.php updates.
+ * Perform Drupal 7.x to 8.x updates that are required for update.php
+ * to function properly.
  *
  * This function runs when update.php is run the first time for 8.x,
  * even before updates are selected or performed. It is important
@@ -624,7 +625,7 @@ function update_fix_d8_requirements() {
 }
 
 /**
- * Installs a new module in Drupal 8 via hook_update_N().
+ * Helper function to install a new module in Drupal 8 via hook_update_N().
  */
 function update_module_enable(array $modules) {
   $schema_store = drupal_container()->get('keyvalue')->get('system.schema');
@@ -663,7 +664,7 @@ function update_module_enable(array $modules) {
 }
 
 /**
- * Performs one update and stores the results for display on the results page.
+ * Perform one update and store the results for display on finished page.
  *
  * If an update function completes successfully, it should return a message
  * as a string indicating success, for example:
@@ -761,7 +762,7 @@ function update_do_one($module, $number, $dependency_map, &$context) {
 }
 
 /**
- * Starts the database update batch process.
+ * Start the database update batch process.
  *
  * @param $start
  *   An array whose keys contain the names of modules to be updated during the
@@ -839,7 +840,7 @@ function update_batch($start, $redirect = NULL, $url = NULL, $batch = array(), $
 }
 
 /**
- * Finishes the update process and stores the results for eventual display.
+ * Finish the update process and store results for eventual display.
  *
  * After the updates run, all caches are flushed. The update results are
  * stored into the session (for example, to be displayed on the update results
@@ -874,7 +875,7 @@ function update_finished($success, $results, $operations) {
 }
 
 /**
- * Returns a list of all the pending database updates.
+ * Return a list of all the pending database updates.
  *
  * @return
  *   An associative array keyed by module name which contains all information
@@ -964,8 +965,8 @@ function update_get_update_list() {
  *   containing all the keys provided by the
  *   Drupal\Component\Graph\Graph::searchAndSort() algorithm, which encode
  *   detailed information about the dependency chain for this update function
- *   (for example: 'paths', 'reverse_paths', 'weight', and 'component'), as
- *   well as the following additional keys:
+ *   (for example: 'paths', 'reverse_paths', 'weight', and 'component'), as well
+ *   as the following additional keys:
  *   - 'allowed': A boolean which is TRUE when the update function's
  *     dependencies are met, and FALSE otherwise. Calling functions should
  *     inspect this value before running the update.
@@ -1170,7 +1171,7 @@ function update_already_performed($module, $number) {
 }
 
 /**
- * Invokes hook_update_dependencies() in all installed modules.
+ * Invoke hook_update_dependencies() in all installed modules.
  *
  * This function is similar to module_invoke_all(), with the main difference
  * that it does not require that a module be enabled to invoke its hook, only
@@ -1306,10 +1307,10 @@ function update_variable_del($name) {
 }
 
 /**
- * Updates config with values set on Drupal 7.x.
+ * Updates config with values set on Drupal 7.x
  *
- * Provides a generalised method to migrate variables from Drupal 7 to
- * Drupal 8's configuration management system.
+ * Provide a generalised method to migrate variables from Drupal 7 to Drupal 8's
+ * configuration management system.
  *
  * @param string $config_name
  *   The configuration object name to retrieve.
diff --git a/core/includes/utility.inc b/core/includes/utility.inc
index f651fd6..5019852 100644
--- a/core/includes/utility.inc
+++ b/core/includes/utility.inc
@@ -12,7 +12,6 @@
  *   The variable to export.
  * @param $prefix
  *   A prefix that will be added at the beginning of every lines of the output.
- *
  * @return
  *   The variable exported in a way compatible to Drupal's coding standards.
  */
diff --git a/core/lib/Drupal/Core/Ajax/AjaxResponse.php b/core/lib/Drupal/Core/Ajax/AjaxResponse.php
index d87c4a6..516325b 100644
--- a/core/lib/Drupal/Core/Ajax/AjaxResponse.php
+++ b/core/lib/Drupal/Core/Ajax/AjaxResponse.php
@@ -93,8 +93,8 @@ protected function ajaxRender(Request $request) {
         //   reliably diffed with array_diff_key(), since the number can change
         //   due to factors unrelated to the inline content, so for now, we
         //   strip the inline items from Ajax responses, and can add support for
-        //   them when drupal_add_css() and drupal_add_js() are changed to use
-        //   a hash of the inline content as the array key.
+        //   them when drupal_add_css() and drupal_add_js() are changed to using
+        //   md5() or some other hash of the inline content.
         foreach ($items[$type] as $key => $item) {
           if (is_numeric($key)) {
             unset($items[$type][$key]);
diff --git a/core/lib/Drupal/Core/Config/Config.php b/core/lib/Drupal/Core/Config/Config.php
index c1f0632..783c6b8 100644
--- a/core/lib/Drupal/Core/Config/Config.php
+++ b/core/lib/Drupal/Core/Config/Config.php
@@ -8,7 +8,6 @@
 namespace Drupal\Core\Config;
 
 use Drupal\Component\Utility\NestedArray;
-use Drupal\Core\Config\ConfigNameException;
 use Symfony\Component\EventDispatcher\EventDispatcher;
 
 /**
@@ -17,18 +16,6 @@
 class Config {
 
   /**
-   * The maximum length of a configuration object name.
-   *
-   * Many filesystems (including HFS, NTFS, and ext4) have a maximum file name
-   * length of 255 characters. To ensure that no configuration objects
-   * incompatible with this limitation are created, we enforce a maximum name
-   * length of 250 characters (leaving 5 characters for the file extension).
-   *
-   * @see http://en.wikipedia.org/wiki/Comparison_of_file_systems
-   */
-  const MAX_NAME_LENGTH = 250;
-
-  /**
    * The name of the configuration object.
    *
    * @var string
@@ -136,37 +123,6 @@ public function setName($name) {
   }
 
   /**
-   * Validates the configuration object name.
-   *
-   * @throws \Drupal\Core\Config\ConfigNameException
-   *
-   * @see Config::MAX_NAME_LENGTH
-   */
-  public static function validateName($name) {
-    // The name must be namespaced by owner.
-    if (strpos($name, '.') === FALSE) {
-      throw new ConfigNameException(format_string('Missing namespace in Config object name @name.', array(
-        '@name' => $name,
-      )));
-    }
-    // The name must be shorter than Config::MAX_NAME_LENGTH characters.
-    if (strlen($name) > self::MAX_NAME_LENGTH) {
-      throw new ConfigNameException(format_string('Config object name @name exceeds maximum allowed length of @length characters.', array(
-        '@name' => $name,
-        '@length' => self::MAX_NAME_LENGTH,
-      )));
-    }
-
-    // The name must not contain any of the following characters:
-    // : ? * < > " ' / \
-    if (preg_match('/[:?*<>"\'\/\\\\]/', $name)) {
-      throw new ConfigNameException(format_string('Invalid character in Config object name @name.', array(
-        '@name' => $name,
-      )));
-    }
-  }
-
-  /**
    * Returns whether this configuration object is new.
    *
    * @return bool
@@ -434,8 +390,6 @@ public function load() {
    *   The configuration object.
    */
   public function save() {
-    // Validate the configuration object name before saving.
-    static::validateName($this->name);
     if (!$this->isLoaded) {
       $this->load();
     }
@@ -494,7 +448,7 @@ protected function notify($config_event_name) {
     $this->eventDispatcher->dispatch('config.' . $config_event_name, new ConfigEvent($this));
   }
 
-  /**
+  /*
    * Merges data into a configuration object.
    *
    * @param array $data_to_merge
diff --git a/core/lib/Drupal/Core/Config/ConfigNameException.php b/core/lib/Drupal/Core/Config/ConfigNameException.php
deleted file mode 100644
index bc4cabb..0000000
--- a/core/lib/Drupal/Core/Config/ConfigNameException.php
+++ /dev/null
@@ -1,13 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains \Drupal\Core\Config\ConfigNameException.
- */
-
-namespace Drupal\Core\Config;
-
-/**
- * Exception thrown when a config object name is invalid.
- */
-class ConfigNameException extends ConfigException {}
diff --git a/core/lib/Drupal/Core/Entity/DatabaseStorageController.php b/core/lib/Drupal/Core/Entity/DatabaseStorageController.php
index e6d8fe6..f8138de 100644
--- a/core/lib/Drupal/Core/Entity/DatabaseStorageController.php
+++ b/core/lib/Drupal/Core/Entity/DatabaseStorageController.php
@@ -9,6 +9,7 @@
 
 use PDO;
 use Drupal\Core\Entity\Query\QueryInterface;
+use Exception;
 use Drupal\Component\Uuid\Uuid;
 use Drupal\Component\Utility\NestedArray;
 
@@ -491,7 +492,7 @@ public function delete(array $entities) {
       // Ignore slave server temporarily.
       db_ignore_slave();
     }
-    catch (\Exception $e) {
+    catch (Exception $e) {
       $transaction->rollback();
       watchdog_exception($this->entityType, $e);
       throw new EntityStorageException($e->getMessage, $e->getCode, $e);
@@ -547,7 +548,7 @@ public function save(EntityInterface $entity) {
 
       return $return;
     }
-    catch (\Exception $e) {
+    catch (Exception $e) {
       $transaction->rollback();
       watchdog_exception($this->entityType, $e);
       throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
diff --git a/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php b/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php
index fd8248e..9d68d9b 100644
--- a/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php
+++ b/core/lib/Drupal/Core/Entity/DatabaseStorageControllerNG.php
@@ -217,7 +217,7 @@ public function save(EntityInterface $entity) {
 
       return $return;
     }
-    catch (\Exception $e) {
+    catch (Exception $e) {
       $transaction->rollback();
       watchdog_exception($this->entityType, $e);
       throw new EntityStorageException($e->getMessage(), $e->getCode(), $e);
@@ -290,7 +290,8 @@ protected function invokeHook($hook, EntityInterface $entity) {
   protected function mapToStorageRecord(EntityInterface $entity) {
     $record = new \stdClass();
     foreach ($this->entityInfo['schema_fields_sql']['base_table'] as $name) {
-      $record->$name = $entity->$name->value;
+      $key = key($entity->$name->offsetGet(0)->getProperties());
+      $record->$name = $entity->$name->{$key};
     }
     return $record;
   }
@@ -301,7 +302,8 @@ protected function mapToStorageRecord(EntityInterface $entity) {
   protected function mapToRevisionStorageRecord(EntityInterface $entity) {
     $record = new \stdClass();
     foreach ($this->entityInfo['schema_fields_sql']['revision_table'] as $name) {
-      $record->$name = $entity->$name->value;
+      $key = key($entity->$name->offsetGet(0)->getProperties());
+      $record->$name = $entity->$name->{$key};
     }
     return $record;
   }
diff --git a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
index 6c4a6fc..76f4d2c 100644
--- a/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
+++ b/core/lib/Drupal/Core/Entity/Field/Type/EntityReferenceItem.php
@@ -2,19 +2,19 @@
 
 /**
  * @file
- * Definition of Drupal\Core\Entity\Field\Type\EntityReferenceItem.
+ * Contains Drupal\Core\Entity\Field\Type\EntityReferenceItem.
  */
 
 namespace Drupal\Core\Entity\Field\Type;
 
 use Drupal\Core\Entity\Field\FieldItemBase;
-use InvalidArgumentException;
+use Drupal\Core\TypedData\ContextAwareInterface;
 
 /**
- * Defines the 'entityreference_field' entity field item.
+ * Defines the 'entity_reference' entity field item.
  *
- * Available settings (below the definition's 'settings' key) are:
- *   - entity type: (required) The entity type to reference.
+ * Required settings (below the definition's 'settings' key) are:
+ *  - target_type: The entity type to reference.
  */
 class EntityReferenceItem extends FieldItemBase {
 
@@ -28,36 +28,36 @@ class EntityReferenceItem extends FieldItemBase {
   static $propertyDefinitions;
 
   /**
-   * Implements ComplexDataInterface::getPropertyDefinitions().
+   * Implements Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinitions().
    */
   public function getPropertyDefinitions() {
     // Definitions vary by entity type, so key them by entity type.
-    $entity_type = $this->definition['settings']['entity type'];
+    $target_type = $this->definition['settings']['target_type'];
 
-    if (!isset(self::$propertyDefinitions[$entity_type])) {
-      self::$propertyDefinitions[$entity_type]['value'] = array(
+    if (!isset(self::$propertyDefinitions[$target_type])) {
+      self::$propertyDefinitions[$target_type]['target_id'] = array(
         // @todo: Lookup the entity type's ID data type and use it here.
         'type' => 'integer',
         'label' => t('Entity ID'),
       );
-      self::$propertyDefinitions[$entity_type]['entity'] = array(
+      self::$propertyDefinitions[$target_type]['entity'] = array(
         'type' => 'entity',
         'constraints' => array(
-          'entity type' => $entity_type,
+          'entity type' => $target_type,
         ),
         'label' => t('Entity'),
         'description' => t('The referenced entity'),
-        // The entity object is computed out of the entity id.
+        // The entity object is computed out of the entity ID.
         'computed' => TRUE,
         'read-only' => FALSE,
-        'settings' => array('id source' => 'value'),
+        'settings' => array('id source' => 'target_id'),
       );
     }
-    return self::$propertyDefinitions[$entity_type];
+    return self::$propertyDefinitions[$target_type];
   }
 
   /**
-   * Overrides FieldItemBase::setValue().
+   * Overrides Drupal\Core\Entity\Field\FieldItemBase::setValue().
    */
   public function setValue($values) {
     // Treat the values as property value of the entity field, if no array
@@ -68,8 +68,8 @@ public function setValue($values) {
 
     // Entity is computed out of the ID, so we only need to update the ID. Only
     // set the entity field if no ID is given.
-    if (isset($values['value'])) {
-      $this->properties['value']->setValue($values['value']);
+    if (isset($values['target_id'])) {
+      $this->properties['target_id']->setValue($values['target_id']);
     }
     elseif (isset($values['entity'])) {
       $this->properties['entity']->setValue($values['entity']);
@@ -77,9 +77,9 @@ public function setValue($values) {
     else {
       $this->properties['entity']->setValue(NULL);
     }
-    unset($values['entity'], $values['value']);
+    unset($values['entity'], $values['target_id']);
     if ($values) {
-      throw new InvalidArgumentException('Property ' . key($values) . ' is unknown.');
+      throw new \InvalidArgumentException('Property ' . key($values) . ' is unknown.');
     }
   }
 }
diff --git a/core/lib/Drupal/Core/Password/PhpassHashedPassword.php b/core/lib/Drupal/Core/Password/PhpassHashedPassword.php
index 157e14c..d5ae542 100644
--- a/core/lib/Drupal/Core/Password/PhpassHashedPassword.php
+++ b/core/lib/Drupal/Core/Password/PhpassHashedPassword.php
@@ -56,7 +56,7 @@ function __construct($countLog2) {
   }
 
   /**
-   * Encodes bytes into printable base 64 using the *nix standard from crypt().
+   * Encode bytes into printable base 64 using the *nix standard from crypt().
    *
    * @param String $input
    *   The string containing bytes to encode.
diff --git a/core/modules/block/block.module b/core/modules/block/block.module
index d9155c3..a31feec 100644
--- a/core/modules/block/block.module
+++ b/core/modules/block/block.module
@@ -662,7 +662,7 @@ function block_menu_delete($menu) {
   $block_configs = config_get_storage_names_with_prefix('plugin.core.block');
   foreach ($block_configs as $config_id) {
     $config = config($config_id);
-    if ($config->get('id') == 'menu_menu_block:' . $menu->id()) {
+    if ($config->get('id') == 'menu_menu_block:' . $menu['menu_name']) {
       $config->delete();
     }
   }
diff --git a/core/modules/block/lib/Drupal/block/BlockBase.php b/core/modules/block/lib/Drupal/block/BlockBase.php
index 7d1356b..b8f770d 100644
--- a/core/modules/block/lib/Drupal/block/BlockBase.php
+++ b/core/modules/block/lib/Drupal/block/BlockBase.php
@@ -287,14 +287,18 @@ public function form($form, &$form_state) {
 
 
     // Visibility settings.
+    $form['visibility_title'] = array(
+      '#type' => 'item',
+      '#title' => t('Visibility settings'),
+      '#weight' => 10,
+    );
     $form['visibility'] = array(
       '#type' => 'vertical_tabs',
-      '#title' => t('Visibility settings'),
       '#attached' => array(
         'js' => array(drupal_get_path('module', 'block') . '/block.js'),
       ),
       '#tree' => TRUE,
-      '#weight' => 10,
+      '#weight' => 15,
     );
 
     // Per-path visibility.
diff --git a/core/modules/block/lib/Drupal/block/Plugin/views/display/Block.php b/core/modules/block/lib/Drupal/block/Plugin/views/display/Block.php
index 04c5f04..0495e1b 100644
--- a/core/modules/block/lib/Drupal/block/Plugin/views/display/Block.php
+++ b/core/modules/block/lib/Drupal/block/Plugin/views/display/Block.php
@@ -163,6 +163,9 @@ public function buildOptionsForm(&$form, &$form_state) {
   public function submitOptionsForm(&$form, &$form_state) {
     parent::submitOptionsForm($form, $form_state);
     switch ($form_state['section']) {
+      case 'display_id':
+        $this->updateBlockBid($form_state['view']->storage->get('name'), $this->display['id'], $this->display['new_id']);
+        break;
       case 'block_description':
         $this->setOption('block_description', $form_state['values']['block_description']);
         break;
@@ -182,4 +185,36 @@ public function usesExposed() {
       return FALSE;
     }
 
+  /**
+   * Update the block delta when you change the machine readable name of the display.
+   */
+  protected function updateBlockBid($name, $old_delta, $delta) {
+    $old_hashes = $hashes = state()->get('views_block_hashes');
+
+    $old_delta = $name . '-' . $old_delta;
+    $delta = $name . '-' . $delta;
+    if (strlen($old_delta) >= 32) {
+      $old_delta = md5($old_delta);
+      unset($hashes[$old_delta]);
+    }
+    if (strlen($delta) >= 32) {
+      $md5_delta = md5($delta);
+      $hashes[$md5_delta] = $delta;
+      $delta = $md5_delta;
+    }
+
+    // Maybe people don't have block module installed, so let's skip this.
+    if (db_table_exists('block')) {
+      db_update('block')
+        ->fields(array('delta' => $delta))
+        ->condition('delta', $old_delta)
+        ->execute();
+    }
+
+    // Update the hashes if needed.
+    if ($hashes != $old_hashes) {
+      state()->set('views_block_hashes', $hashes);
+    }
+  }
+
 }
diff --git a/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php b/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php
new file mode 100644
index 0000000..8010f19
--- /dev/null
+++ b/core/modules/comment/lib/Drupal/comment/Plugin/entity_reference/selection/CommentSelection.php
@@ -0,0 +1,81 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\comment\Plugin\entity_reference\selection\CommentSelection.
+ */
+
+namespace Drupal\comment\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;
+
+/**
+ * Provides specific access control for the comment entity type.
+ *
+ * @Plugin(
+ *   id = "base_comment",
+ *   module = "entity_reference",
+ *   label = @Translation("Comment selection"),
+ *   entity_types = {"comment"},
+ *   group = "base",
+ *   weight = 1
+ * )
+ */
+class CommentSelection extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::buildEntityQuery().
+   */
+  public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = parent::buildEntityQuery($match, $match_operator);
+
+    // Adding the 'comment_access' tag is sadly insufficient for comments:
+    // core requires us to also know about the concept of 'published' and
+    // 'unpublished'.
+    if (!user_access('administer comments')) {
+      $query->condition('status', COMMENT_PUBLISHED);
+    }
+    return $query;
+  }
+
+  /**
+   * Overrides SelectionBase::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) {
+    $tables = $query->getTables();
+    $base_table = $tables['base_table']['alias'];
+
+    // The Comment module doesn't implement any proper comment access,
+    // and as a consequence doesn't make sure that comments cannot be viewed
+    // when the user doesn't have access to the node.
+    $node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
+    // Pass the query to the node access control.
+    $this->reAlterQuery($query, 'node_access', $node_alias);
+
+    // Alas, the comment entity exposes a bundle, but doesn't have a bundle
+    // column in the database. We have to alter the query ourselves to go fetch
+    // the bundle.
+    $conditions = &$query->conditions();
+    foreach ($conditions as $key => &$condition) {
+      if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
+        $condition['field'] = $node_alias . '.type';
+        foreach ($condition['value'] as &$value) {
+          if (substr($value, 0, 13) == 'comment_node_') {
+            $value = substr($value, 13);
+          }
+        }
+        break;
+      }
+    }
+
+    // Passing the query to node_query_node_access_alter() is sadly
+    // insufficient for nodes.
+    // @see SelectionEntityTypeNode::entityQueryAlter()
+    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
+      $query->condition($node_alias . '.status', 1);
+    }
+  }
+}
diff --git a/core/modules/config/lib/Drupal/config/Tests/ConfigCRUDTest.php b/core/modules/config/lib/Drupal/config/Tests/ConfigCRUDTest.php
index a04a928..56e5ecf 100644
--- a/core/modules/config/lib/Drupal/config/Tests/ConfigCRUDTest.php
+++ b/core/modules/config/lib/Drupal/config/Tests/ConfigCRUDTest.php
@@ -7,7 +7,6 @@
 
 namespace Drupal\config\Tests;
 
-use Drupal\Core\Config\ConfigNameException;
 use Drupal\simpletest\DrupalUnitTestBase;
 
 /**
@@ -104,88 +103,4 @@ function testCRUD() {
     $this->assertIdentical($new_config->get('404'), $expected_values['404']);
   }
 
-  /**
-   * Tests the validation of configuration object names.
-   */
-  function testNameValidation() {
-    // Verify that an object name without namespace causes an exception.
-    $name = 'nonamespace';
-    $message = 'Expected ConfigNameException was thrown for a name without a namespace.';
-    try {
-      config($name)->save();
-      $this->fail($message);
-    }
-    catch (ConfigNameException $e) {
-      $this->pass($message);
-    }
-
-    // Verify that a name longer than the maximum length causes an exception.
-    $name = 'config_test.herman_melville.moby_dick_or_the_whale.harper_1851.now_small_fowls_flew_screaming_over_the_yet_yawning_gulf_a_sullen_white_surf_beat_against_its_steep_sides_then_all_collapsed_and_the_great_shroud_of_the_sea_rolled_on_as_it_rolled_five_thousand_years_ago';
-    $message = 'Expected ConfigNameException was thrown for a name longer than Config::MAX_NAME_LENGTH.';
-    try {
-      config($name)->save();
-      $this->fail($message);
-    }
-    catch (ConfigNameException $e) {
-      $this->pass($message);
-    }
-
-    // Verify that disallowed characters in the name cause an exception.
-    $characters = $test_characters = array(':', '?', '*', '<', '>', '"', '\'', '/', '\\');
-    foreach ($test_characters as $i => $c) {
-      try {
-        $name = 'namespace.object' . $c;
-        $config = config($name);
-        $config->save();
-      }
-      catch (ConfigNameException $e) {
-        unset($test_characters[$i]);
-      }
-    }
-    $this->assertTrue(empty($test_characters), format_string('Expected ConfigNameException was thrown for all invalid name characters: @characters', array(
-      '@characters' => implode(' ', $characters),
-    )));
-
-    // Verify that a valid config object name can be saved.
-    $name = 'namespace.object';
-    $message = 'ConfigNameException was not thrown for a valid object name.';
-    try {
-      $config = config($name);
-      $config->save();
-      $this->pass($message);
-    }
-    catch (\Exception $e) {
-      $this->fail($message);
-    }
-
-    // Verify an exception is thrown when importing configuration with an
-    // invalid name (missing a namespace).
-    $message = 'Expected ConfigNameException was thrown when attempting to install invalid configuration.';
-    try {
-      $this->enableModules(array('config_test_invalid_name'));
-      $this->fail($message);
-    }
-    catch (ConfigNameException $e) {
-      $this->pass($message);
-    }
-
-    // Write configuration with an invalid name (missing a namespace) to
-    // staging.
-    $storage = $this->container->get('config.storage');
-    $staging = $this->container->get('config.storage.staging');
-    $manifest_data = config('manifest.invalid_object_name')->get();
-    $manifest_data['new']['name'] = 'invalid';
-    $staging->write('manifest.invalid_object_name', $manifest_data);
-
-    // Verify that an exception is thrown when synchronizing.
-    $message = 'Expected ConfigNameException was thrown when attempting to sync invalid configuration.';
-    try {
-      config_import();
-      $this->fail($message);
-    }
-    catch (ConfigNameException $e) {
-      $this->pass($message);
-    }
-  }
-
 }
diff --git a/core/modules/config/tests/config_test_invalid_name/config/invalid_object_name.yml b/core/modules/config/tests/config_test_invalid_name/config/invalid_object_name.yml
deleted file mode 100644
index f3f2ba0..0000000
--- a/core/modules/config/tests/config_test_invalid_name/config/invalid_object_name.yml
+++ /dev/null
@@ -1 +0,0 @@
-frittata: potato
diff --git a/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.info b/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.info
deleted file mode 100644
index 8532cdb..0000000
--- a/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.info
+++ /dev/null
@@ -1,5 +0,0 @@
-name = Invalid configuration name
-package = Core
-version = VERSION
-core = 8.x
-hidden = TRUE
diff --git a/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.module b/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.module
deleted file mode 100644
index 890776d..0000000
--- a/core/modules/config/tests/config_test_invalid_name/config_test_invalid_name.module
+++ /dev/null
@@ -1,6 +0,0 @@
-<?php
-
-/**
- * @file
- * Test module containing a configuration file with an invalid name.
- */
diff --git a/core/modules/contact/lib/Drupal/contact/Tests/Views/ContactFieldsTest.php b/core/modules/contact/lib/Drupal/contact/Tests/Views/ContactFieldsTest.php
deleted file mode 100644
index 7170030..0000000
--- a/core/modules/contact/lib/Drupal/contact/Tests/Views/ContactFieldsTest.php
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains \Drupal\contact\Tests\Views\ContactFieldsTest.
- */
-
-namespace Drupal\contact\Tests\Views;
-
-use Drupal\views\Tests\ViewTestBase;
-
-/**
- * Tests which checks that no fieldapi fields are added on contact.
- */
-class ContactFieldsTest extends ViewTestBase {
-
-  /**
-   * Modules to enable.
-   *
-   * @var array
-   */
-  public static $modules = array('field', 'text', 'contact');
-
-  /**
-   * Contains the field definition array attached to contact used for this test.
-   *
-   * @var array
-   */
-  protected $field;
-
-  public static function getInfo() {
-    return array(
-      'name' => 'Contact: Field views data',
-      'description' => 'Tests which checks that no fieldapi fields are added on contact.',
-      'group' => 'Views Modules',
-    );
-  }
-
-  protected function setUp() {
-    parent::setUp();
-
-    $field = array(
-      'field_name' => strtolower($this->randomName()),
-      'type' => 'text'
-    );
-
-    $this->field = field_create_field($field);
-
-    $instance = array(
-      'field_name' => $field['field_name'],
-      'entity_type' => 'contact_message',
-      'bundle' => 'contact_message',
-    );
-    field_create_instance($instance);
-  }
-
-  /**
-   * Tests the views data generation.
-   */
-  public function testViewsData() {
-    $field_name = $this->field['field_name'];
-    $table_name = _field_sql_storage_tablename($this->field);
-    $data = drupal_container()->get('views.views_data')->get($table_name);
-
-    // Test that the expected data array is returned.
-    $expected = array('', '_value', '_format');
-    $this->assertEqual(count($data), count($expected), 'The expected amount of array keys were found.');
-    foreach ($expected as $suffix) {
-      $this->assertTrue(isset($data[$field_name . $suffix]));
-    }
-    $this->assertTrue(empty($data['table']['join']), 'The field is not joined to the non existent contact message base table.');
-  }
-
-}
diff --git a/core/modules/entity_reference/css/entity_reference-rtl.admin.css b/core/modules/entity_reference/css/entity_reference-rtl.admin.css
new file mode 100644
index 0000000..3302ab8
--- /dev/null
+++ b/core/modules/entity_reference/css/entity_reference-rtl.admin.css
@@ -0,0 +1,4 @@
+
+.entity_reference-settings {
+  margin-right: 1.5em;
+}
diff --git a/core/modules/entity_reference/css/entity_reference.admin.css b/core/modules/entity_reference/css/entity_reference.admin.css
new file mode 100644
index 0000000..d608ccf
--- /dev/null
+++ b/core/modules/entity_reference/css/entity_reference.admin.css
@@ -0,0 +1,4 @@
+
+.entity_reference-settings {
+  margin-left: 1.5em; /* LTR */
+}
diff --git a/core/modules/entity_reference/entity_reference.info b/core/modules/entity_reference/entity_reference.info
new file mode 100644
index 0000000..2216092
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.info
@@ -0,0 +1,6 @@
+name = Entity Reference
+description = Provides a field that can reference other entities.
+package = Core
+version = VERSION
+core = 8.x
+dependencies[] = field
diff --git a/core/modules/entity_reference/entity_reference.install b/core/modules/entity_reference/entity_reference.install
new file mode 100644
index 0000000..17030ef
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.install
@@ -0,0 +1,49 @@
+<?php
+
+/**
+ * @file
+ * Install, update and uninstall functions for the Entity reference
+ * module.
+ */
+
+/**
+ * Implements hook_field_schema().
+ */
+function entity_reference_field_schema($field) {
+  $schema = array(
+    'columns' => array(
+      'target_id' => array(
+        'description' => 'The ID of the target entity.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => TRUE,
+      ),
+      'revision_id' => array(
+        'description' => 'The revision ID of the target entity.',
+        'type' => 'int',
+        'unsigned' => TRUE,
+        'not null' => FALSE,
+      ),
+    ),
+    'indexes' => array(
+      'target_id' => array('target_id'),
+    ),
+    'foreign keys' => array(),
+  );
+
+  // Create a foreign key to the target entity type base type.
+  // @todo It's still not safe to call entity_get_info() in here.
+  // see http://drupal.org/node/1847582
+  //  $entity_type = $field['settings']['target_type'];
+  //  $entity_info = entity_get_info($entity_type);
+  //
+  //  $base_table = $entity_info['base_table'];
+  //  $id_column = $entity_info['entity_keys']['id'];
+  //
+  //  $schema['foreign keys'][$base_table] = array(
+  //    'table' => $base_table,
+  //    'columns' => array('target_id' => $id_column),
+  //  );
+
+  return $schema;
+}
diff --git a/core/modules/entity_reference/entity_reference.module b/core/modules/entity_reference/entity_reference.module
new file mode 100644
index 0000000..0b2eca9
--- /dev/null
+++ b/core/modules/entity_reference/entity_reference.module
@@ -0,0 +1,543 @@
+<?php
+
+/**
+ * @file
+ * Provides a field that can reference other entities.
+ */
+
+use Symfony\Component\HttpFoundation\JsonResponse;
+use Drupal\Component\Utility\NestedArray;
+use Drupal\Core\Database\Query\AlterableInterface;
+use Drupal\Core\Entity\EntityInterface;
+
+/**
+ * Implements hook_field_info().
+ */
+function entity_reference_field_info() {
+  $field_info['entity_reference'] = array(
+    'label' => t('Entity Reference'),
+    'description' => t('This field references another entity.'),
+    'settings' => array(
+      // Default to a primary entity type (i.e. node or user).
+      'target_type' => module_exists('node') ? 'node' : 'user',
+    ),
+    'instance_settings' => array(
+      // The selection handler for this instance.
+      'handler' => 'base',
+      // The handler settings.
+      'handler_settings' => array(),
+    ),
+    'default_widget' => 'entity_reference_autocomplete',
+    'default_formatter' => 'entity_reference_label',
+    'field item class' => 'Drupal\Core\Entity\Field\Type\EntityReferenceItem',
+  );
+  return $field_info;
+}
+
+/**
+ * Implements hook_entity_field_info().
+ *
+ * Set the "target_type" property definition for entity reference fields.
+ *
+ * @see Drupal\Core\Entity\Field\Type\EntityReferenceItem::getPropertyDefinitions()
+ */
+function entity_reference_entity_field_info($entity_type) {
+  $property_info = array();
+  foreach (field_info_instances($entity_type) as $bundle_name => $instances) {
+    foreach ($instances as $field_name => $instance) {
+      $field = field_info_field($field_name);
+      if ($field['type'] != 'entity_reference') {
+        continue;
+      }
+      $property_info['definitions'][$field_name]['settings']['target_type'] = $field['settings']['target_type'];
+    }
+  }
+  return $property_info;
+}
+
+/**
+ * Implements hook_menu().
+ */
+function entity_reference_menu() {
+  $items = array();
+
+  $items['entity_reference/autocomplete/single/%/%/%'] = array(
+    'title' => 'Entity Reference Autocomplete',
+    'page callback' => 'entity_reference_autocomplete_callback',
+    'page arguments' => array(2, 3, 4, 5),
+    'access callback' => 'entity_reference_autocomplete_access_callback',
+    'access arguments' => array(2, 3, 4, 5),
+    'type' => MENU_CALLBACK,
+  );
+  $items['entity_reference/autocomplete/tags/%/%/%'] = array(
+    'title' => 'Entity Reference Autocomplete',
+    'page callback' => 'entity_reference_autocomplete_callback',
+    'page arguments' => array(2, 3, 4, 5),
+    'access callback' => 'entity_reference_autocomplete_access_callback',
+    'access arguments' => array(2, 3, 4, 5),
+    'type' => MENU_CALLBACK,
+  );
+
+  return $items;
+}
+
+/**
+ * Gets the selection handler for a given entity_reference field.
+ */
+function entity_reference_get_selection_handler($field, $instance, EntityInterface $entity = NULL) {
+  $options = array(
+    'field' => $field,
+    'instance' => $instance,
+    'entity' => $entity,
+  );
+  return drupal_container()->get('plugin.manager.entity_reference.selection')->getInstance($options);
+}
+
+/**
+ * Implements hook_field_is_empty().
+ */
+function entity_reference_field_is_empty($item, $field) {
+  if (!empty($item['target_id']) && $item['target_id'] == 'auto_create') {
+    // Allow auto-create entities.
+    return FALSE;
+  }
+  return !isset($item['target_id']) || !is_numeric($item['target_id']);
+}
+
+/**
+ * Implements hook_field_presave().
+ *
+ * Create an entity on the fly.
+ */
+function entity_reference_field_presave(EntityInterface $entity, $field, $instance, $langcode, &$items) {
+  global $user;
+  $target_type = $field['settings']['target_type'];
+  $entity_info = entity_get_info($target_type);
+
+  // Get the bundle.
+  if (!empty($instance['settings']['handler_settings']['target_bundles']) && count($instance['settings']['handler_settings']['target_bundles']) == 1) {
+    $bundle = reset($instance['settings']['handler_settings']['target_bundles']);
+  }
+  else {
+    $bundle = reset($entity_info['bundles']);
+  }
+
+  foreach ($items as $delta => $item) {
+    if ($item['target_id'] == 'auto_create') {
+      $bundle_key = $entity_info['entity_keys']['bundle'];
+      $label_key = $entity_info['entity_keys']['label'];
+      $values = array(
+        $label_key => $item['label'],
+        $bundle_key => $bundle,
+        // @todo: Use wrapper to get the user if exists or needed.
+        'uid' => !empty($entity->uid) ? $entity->uid : $user->uid,
+      );
+      $target_entity = entity_create($target_type, $values);
+      $target_entity->save();
+      $items[$delta]['target_id'] = $target_entity->id();
+    }
+  }
+}
+
+
+/**
+ * Implements hook_field_validate().
+ */
+function entity_reference_field_validate(EntityInterface $entity = NULL, $field, $instance, $langcode, $items, &$errors) {
+  $ids = array();
+  foreach ($items as $delta => $item) {
+    if (!entity_reference_field_is_empty($item, $field) && $item['target_id'] !== 'auto_create') {
+      $ids[$item['target_id']] = $delta;
+    }
+  }
+
+  if ($ids) {
+    $valid_ids = entity_reference_get_selection_handler($field, $instance, $entity)->validateReferencableEntities(array_keys($ids));
+
+    $invalid_entities = array_diff_key($ids, array_flip($valid_ids));
+    if ($invalid_entities) {
+      foreach ($invalid_entities as $id => $delta) {
+        $errors[$field['field_name']][$langcode][$delta][] = array(
+          'error' => 'entity_reference_invalid_entity',
+          'message' => t('The referenced entity (@type: @id) does not exist.', array('@type' => $field['settings']['target_type'], '@id' => $id)),
+        );
+      }
+    }
+  }
+}
+
+/**
+ * Implements hook_field_settings_form().
+ */
+function entity_reference_field_settings_form($field, $instance, $has_data) {
+  // Select the target entity type.
+  $entity_type_options = array();
+  foreach (entity_get_info() as $entity_type => $entity_info) {
+    // @todo Remove this ugly hack, needed for now because Config entities have
+    // no EFQ support. Revisit after http://drupal.org/node/1853856 and
+    // http://drupal.org/node/1846454.
+    if (!is_subclass_of($entity_info['class'], '\Drupal\Core\Config\Entity\ConfigEntityBase')) {
+      $entity_type_options[$entity_type] = $entity_info['label'];
+    }
+  }
+
+  $form['target_type'] = array(
+    '#type' => 'select',
+    '#title' => t('Target type'),
+    '#options' => $entity_type_options,
+    '#default_value' => $field['settings']['target_type'],
+    '#required' => TRUE,
+    '#description' => t('The entity type that can be referenced through this field.'),
+    '#disabled' => $has_data,
+    '#size' => 1,
+  );
+
+  return $form;
+}
+
+/**
+ * Implements hook_field_instance_settings_form().
+ *
+ * The field settings infrastructure is not AJAX enabled by default,
+ * because it doesn't pass over the $form_state.
+ * Build the whole form into a #process in which we actually have access
+ * to the form state.
+ */
+function entity_reference_field_instance_settings_form($field, $instance) {
+  $form['entity_reference_wrapper'] = array(
+    '#type' => 'container',
+    '#attached' => array(
+      'css' => array(drupal_get_path('module', 'entity_reference') . '/css/entity_reference.admin.css'),
+    ),
+    '#process' => array(
+      '_entity_reference_field_instance_settings_process',
+      '_entity_reference_field_instance_settings_ajax_process',
+    ),
+    '#element_validate' => array('_entity_reference_field_instance_settings_validate'),
+    '#field' => $field,
+    '#instance' => $instance->definition,
+  );
+  return $form;
+}
+
+/**
+ * Render API callback: Processes the field settings form and allows access to
+ * the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_process($form, $form_state) {
+  $field = isset($form_state['entity_reference']['field']) ? $form_state['entity_reference']['field'] : $form['#field'];
+  $instance = isset($form_state['entity_reference']['instance']) ? $form_state['entity_reference']['instance'] : $form['#instance'];
+
+  $settings = $instance['settings'];
+  $settings += array('handler' => 'base');
+
+  // Get all selection plugins for this entity type.
+  $selection_plugins = drupal_container()->get('plugin.manager.entity_reference.selection')->getSelectionGroups($field['settings']['target_type']);
+  $handler_groups = array_keys($selection_plugins);
+
+  $handlers = drupal_container()->get('plugin.manager.entity_reference.selection')->getDefinitions();
+  $handlers_options = array();
+  foreach ($handlers as $plugin_id => $plugin) {
+    // We only display base plugins (e.g. 'base', 'views', ..) and not entity
+    // type specific plugins (e.g. 'base_node', 'base_user', ...).
+    if (in_array($plugin_id, $handler_groups)) {
+      $handlers_options[$plugin_id] = check_plain($plugin['label']);
+    }
+  }
+
+  $form['handler'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Selection'),
+    '#tree' => TRUE,
+    '#process' => array('_entity_reference_form_process_merge_parent'),
+  );
+
+  $form['handler']['handler'] = array(
+    '#type' => 'select',
+    '#title' => t('Method'),
+    '#options' => $handlers_options,
+    '#default_value' => $settings['handler'],
+    '#required' => TRUE,
+    '#ajax' => TRUE,
+    '#limit_validation_errors' => array(),
+  );
+  $form['handler']['handler_submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Change handler'),
+    '#limit_validation_errors' => array(),
+    '#attributes' => array(
+      'class' => array('js-hide'),
+    ),
+    '#submit' => array('entity_reference_settings_ajax_submit'),
+  );
+
+  $form['handler']['handler_settings'] = array(
+    '#type' => 'container',
+    '#attributes' => array('class' => array('entity_reference-settings')),
+  );
+
+  $handler = entity_reference_get_selection_handler($field, $instance);
+  $form['handler']['handler_settings'] += $handler->settingsForm($field, $instance);
+
+  return $form;
+}
+
+/**
+ * Render API callback: Processes the field instance settings form and allows
+ * access to the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_ajax_process($form, $form_state) {
+  _entity_reference_field_instance_settings_ajax_process_element($form, $form);
+  return $form;
+}
+
+/**
+ * Adds entity_reference specific properties to AJAX form elements from the
+ * field instance settings form.
+ *
+ * @see _entity_reference_field_instance_settings_ajax_process()
+ */
+function _entity_reference_field_instance_settings_ajax_process_element(&$element, $main_form) {
+  if (!empty($element['#ajax'])) {
+    $element['#ajax'] = array(
+      'callback' => 'entity_reference_settings_ajax',
+      'wrapper' => $main_form['#id'],
+      'element' => $main_form['#array_parents'],
+    );
+  }
+
+  foreach (element_children($element) as $key) {
+    _entity_reference_field_instance_settings_ajax_process_element($element[$key], $main_form);
+  }
+}
+
+/**
+ * Render API callback: Moves entity_reference specific Form API elements
+ * (i.e. 'handler_settings') up a level for easier processing by the validation
+ * and submission handlers.
+ *
+ * @see _entity_reference_field_settings_process()
+ */
+function _entity_reference_form_process_merge_parent($element) {
+  $parents = $element['#parents'];
+  array_pop($parents);
+  // For the 'Selection' fieldset, we need to go one more level above
+  // because of our extra container.
+  if (isset($element['#title']) && $element['#title'] == t('Selection')) {
+    array_pop($parents);
+  }
+  $element['#parents'] = $parents;
+  return $element;
+}
+
+/**
+ * Form element validation handler; Filters the #value property of an element.
+ */
+function _entity_reference_element_validate_filter(&$element, &$form_state) {
+  $element['#value'] = array_filter($element['#value']);
+  form_set_value($element, $element['#value'], $form_state);
+}
+
+/**
+ * Form element validation handler; Stores the new values in the form state.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function _entity_reference_field_instance_settings_validate($form, &$form_state) {
+  $instance = $form['#instance'];
+  if (isset($form_state['values']['instance'])) {
+    $instance['settings'] = $form_state['values']['instance']['settings'];
+  }
+  $form_state['entity_reference']['instance'] = $instance;
+
+  unset($form_state['values']['instance']['settings']['handler_submit']);
+}
+
+/**
+ * Ajax callback for the handler settings form.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function entity_reference_settings_ajax($form, $form_state) {
+  $trigger = $form_state['triggering_element'];
+  return NestedArray::getValue($form, $trigger['#ajax']['element']);
+}
+
+/**
+ * Submit handler for the non-JS case.
+ *
+ * @see entity_reference_field_instance_settings_form()
+ */
+function entity_reference_settings_ajax_submit($form, &$form_state) {
+  $form_state['rebuild'] = TRUE;
+}
+
+/**
+ * Implements hook_options_list().
+ */
+function entity_reference_options_list($field, $instance, $entity_type = NULL, $entity = NULL) {
+  if (!$options = entity_reference_get_selection_handler($field, $instance, $entity)->getReferencableEntities()) {
+    return array();
+  }
+
+  // Rebuild the array by changing the bundle key into the bundle label.
+  $target_type = $field['settings']['target_type'];
+  $entity_info = entity_get_info($target_type);
+
+  $return = array();
+  foreach ($options as $bundle => $entity_ids) {
+    $bundle_label = check_plain($entity_info['bundles'][$bundle]['label']);
+    $return[$bundle_label] = $entity_ids;
+  }
+
+  return count($return) == 1 ? reset($return) : $return;
+}
+
+/**
+ * Implements hook_query_TAG_alter().
+ */
+function entity_reference_query_entity_reference_alter(AlterableInterface $query) {
+  $handler = $query->getMetadata('entity_reference_selection_handler');
+  $handler->entityQueryAlter($query);
+}
+
+/**
+ * Menu Access callback for the autocomplete widget.
+ *
+ * @param string $type
+ *   The widget type (i.e. 'single' or 'tags').
+ * @param string $field_name
+ *   The name of the entity-reference field.
+ * @param string $entity_type
+ *   The entity type.
+ * @param string $bundle_name
+ *   The bundle name.
+ *
+ * @return bool
+ *   TRUE if user can access this menu item, FALSE otherwise.
+ */
+function entity_reference_autocomplete_access_callback($type, $field_name, $entity_type, $bundle_name) {
+  if (!$field = field_info_field($field_name)) {
+    return FALSE;
+  }
+  if (!$instance = field_info_instance($entity_type, $field_name, $bundle_name)){
+    return FALSE;
+  }
+
+  if ($field['type'] != 'entity_reference' || !field_access('edit', $field, $entity_type)) {
+    return FALSE;
+  }
+
+  return TRUE;
+}
+
+/**
+ * Menu callback; Autocomplete the label of an entity.
+ *
+ * @param string $type
+ *   The widget type (i.e. 'single' or 'tags').
+ * @param string $field_name
+ *   The name of the entity-reference field.
+ * @param string $entity_type
+ *   The entity type.
+ * @param string $bundle_name
+ *   The bundle name.
+ * @param string $entity_id
+ *   (optional) The entity ID the entity-reference field is attached to.
+ *   Defaults to ''.
+ *
+ * @return \Symfony\Component\HttpFoundation\JsonResponse
+ */
+function entity_reference_autocomplete_callback($type, $field_name, $entity_type, $bundle_name, $entity_id = '') {
+  $field = field_info_field($field_name);
+  $instance = field_info_instance($entity_type, $field_name, $bundle_name);
+
+  // Get the typed string, if exists from the URL.
+  $tags_typed = drupal_container()->get('request')->query->get('q');
+  $tags_typed = drupal_explode_tags($tags_typed);
+  $string = drupal_strtolower(array_pop($tags_typed));
+
+  return entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id, $string);
+}
+
+/**
+ * Returns JSON data based on a given field, instance and search string.
+ *
+ * This function can be used by other modules that wish to pass a mocked
+ * definition of the field on instance.
+ *
+ * @param string $type
+ *   The widget type (i.e. 'single' or 'tags').
+ * @param array $field
+ *   The field array definition.
+ * @param array $instance
+ *   The instance array definition.
+ * @param string $entity_type
+ *   The entity type.
+ * @param string $entity_id
+ *   (optional) The entity ID the entity-reference field is attached to.
+ *   Defaults to ''.
+ * @param string $string
+ *   The label of the entity to query by.
+ *
+ * @return \Symfony\Component\HttpFoundation\JsonResponse
+ *
+ * @see entity_reference_autocomplete_callback()
+ */
+function entity_reference_autocomplete_callback_get_matches($type, $field, $instance, $entity_type, $entity_id = '', $string = '') {
+  $target_type = $field['settings']['target_type'];
+  $matches = array();
+  $entity = NULL;
+
+  if ($entity_id !== 'NULL') {
+    $entity = entity_load($entity_type, $entity_id);
+    // @todo: Improve when we have entity_access().
+    $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
+    if (!$entity || !$entity_access) {
+      return MENU_ACCESS_DENIED;
+    }
+  }
+  $handler = entity_reference_get_selection_handler($field, $instance, $entity);
+
+  if ($type == 'tags') {
+    // The user enters a comma-separated list of tags. We only autocomplete the
+    // last tag.
+    $tags_typed = drupal_explode_tags($string);
+    $tag_last = drupal_strtolower(array_pop($tags_typed));
+    if (!empty($tag_last)) {
+      $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
+    }
+  }
+  else {
+    // The user enters a single tag.
+    $prefix = '';
+    $tag_last = $string;
+  }
+
+  if (isset($tag_last)) {
+    // Get an array of matching entities.
+    $match_operator = !empty($instance['widget']['settings']['match_operator']) ? $instance['widget']['settings']['match_operator'] : 'CONTAINS';
+    $entity_labels = $handler->getReferencableEntities($tag_last, $match_operator, 10);
+
+    // Loop through the products and convert them into autocomplete output.
+    foreach ($entity_labels as $values) {
+      foreach ($values as $entity_id => $label) {
+        $key = "$label ($entity_id)";
+        // Strip things like starting/trailing white spaces, line breaks and
+        // tags.
+        $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(decode_entities(strip_tags($key)))));
+        // Names containing commas or quotes must be wrapped in quotes.
+        if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
+          $key = '"' . str_replace('"', '""', $key) . '"';
+        }
+        $matches[$prefix . $key] = '<div class="reference-autocomplete">' . $label . '</div>';
+      }
+    }
+  }
+
+  return new JsonResponse($matches);
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php b/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php
new file mode 100644
index 0000000..434937d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/EntityReferenceBundle.php
@@ -0,0 +1,26 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\EntityReferenceBundle.
+ */
+
+namespace Drupal\entity_reference;
+
+use Symfony\Component\DependencyInjection\ContainerBuilder;
+use Symfony\Component\HttpKernel\Bundle\Bundle;
+
+/**
+ * Entity reference dependency injection container.
+ */
+class EntityReferenceBundle extends Bundle {
+
+  /**
+   * Overrides Symfony\Component\HttpKernel\Bundle\Bundle::build().
+   */
+  public function build(ContainerBuilder $container) {
+    // Register the SelectionPluginManager class with the dependency injection
+    // container.
+    $container->register('plugin.manager.entity_reference.selection', 'Drupal\entity_reference\Plugin\Type\SelectionPluginManager');
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.php
new file mode 100644
index 0000000..f8f784d
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Derivative/SelectionBase.php
@@ -0,0 +1,54 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\Derivative\SelectionBase.
+ */
+
+namespace Drupal\entity_reference\Plugin\Derivative;
+
+use Drupal\Component\Plugin\Derivative\DerivativeInterface;
+
+/**
+ * Base class for selection plugins provided by Entity reference.
+ */
+class SelectionBase implements DerivativeInterface {
+
+  /**
+   * Holds the list of plugin derivatives.
+   *
+   * @var array
+   */
+  protected $derivatives = array();
+
+  /**
+   * Implements DerivativeInterface::getDerivativeDefinition().
+   */
+  public function getDerivativeDefinition($derivative_id, array $base_plugin_definition) {
+    if (!empty($this->derivatives) && !empty($this->derivatives[$derivative_id])) {
+      return $this->derivatives[$derivative_id];
+    }
+    $this->getDerivativeDefinitions($base_plugin_definition);
+    return $this->derivatives[$derivative_id];
+  }
+
+  /**
+   * Implements DerivativeInterface::getDerivativeDefinitions().
+   */
+  public function getDerivativeDefinitions(array $base_plugin_definition) {
+    $supported_entities = array(
+      'comment',
+      'file',
+      'node',
+      'taxonomy_term',
+      'user'
+    );
+    foreach (entity_get_info() as $entity_type => $info) {
+      if (!in_array($entity_type, $supported_entities)) {
+        $this->derivatives[$entity_type] = $base_plugin_definition;
+        $this->derivatives[$entity_type]['label'] = t('@enitty_type selection', array('@entity_type' => $info['label']));
+      }
+    }
+    return $this->derivatives;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php
new file mode 100644
index 0000000..31c1cb1
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionBroken.php
@@ -0,0 +1,65 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\Type\Selection\SelectionBroken.
+ */
+
+namespace Drupal\entity_reference\Plugin\Type\Selection;
+
+use Drupal\Core\Database\Query\SelectInterface;
+
+/**
+ * A null implementation of SelectionInterface.
+ */
+class SelectionBroken implements SelectionInterface {
+
+  /**
+   * Constructs a SelectionBroken object.
+   */
+  public function __construct($field, $instance = NULL) {
+    $this->field = $field;
+    $this->instance = $instance;
+  }
+
+  /**
+   * Implements SelectionInterface::settingsForm().
+   */
+  public static function settingsForm(&$field, &$instance) {
+    $form['selection_handler'] = array(
+      '#markup' => t('The selected selection handler is broken.'),
+    );
+    return $form;
+  }
+
+  /**
+   * Implements SelectionInterface::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    return array();
+  }
+
+  /**
+   * Implements SelectionInterface::countReferencableEntities().
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    return 0;
+  }
+
+  /**
+   * Implements SelectionInterface::validateReferencableEntities().
+   */
+  public function validateReferencableEntities(array $ids) {
+    return array();
+  }
+
+  /**
+   * Implements SelectionInterface::validateAutocompleteInput().
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE) { }
+
+  /**
+   * Implements SelectionInterface::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) { }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
new file mode 100644
index 0000000..49ad461
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/Selection/SelectionInterface.php
@@ -0,0 +1,81 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface.
+ */
+
+namespace Drupal\entity_reference\Plugin\Type\Selection;
+
+use Drupal\Core\Database\Query\SelectInterface;
+
+/**
+ * Interface definition for Entity reference selection plugins.
+ *
+ * This interface details the methods that most plugin implementations will want
+ * to override. See Drupal\field\Plugin\Type\Selection\SelectionBaseInterface
+ * for base wrapping methods that should most likely be inherited directly from
+ * Drupal\entity_reference\Plugin\Type\Selection\SelectionBase.
+ */
+interface SelectionInterface {
+
+  /**
+   * Returns a list of referencable entities.
+   *
+   * @return array
+   *   An array of referencable entities, which keys are entity ids and
+   *   values (safe HTML) labels to be displayed to the user.
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0);
+
+  /**
+   * Counts entities that are referencable by a given field.
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS');
+
+  /**
+   * Validates that entities can be referenced by this field.
+   *
+   * @return array
+   *   An array of valid entity IDs.
+   */
+  public function validateReferencableEntities(array $ids);
+
+  /**
+   * Validates input from an autocomplete widget that has no ID.
+   *
+   * @param string $input
+   *   Single string from autocomplete widget.
+   * @param array $element
+   *   The form element to set a form error.
+   * @param boolean $strict
+   *   If TRUE, and an element is not found issue a form error.
+   *
+   * @return integer|null
+   *   Value of a matching entity ID, or NULL if none.
+   *
+   * @see \Drupal\entity_reference\Plugin\field\widget::elementValidate()
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE);
+
+  /**
+   * Allows the selection to alter the SelectQuery generated by EntityFieldQuery.
+   *
+   * @param \Drupal\Core\Database\Query\SelectInterface $query
+   *   A Select Query object.
+   */
+  public function entityQueryAlter(SelectInterface $query);
+
+  /**
+   * Generates the settings form for this selection.
+   *
+   * @param array $field
+   *   A field data structure.
+   * @param array $instance
+   *   A field instance data structure.
+   *
+   * @return array
+   *   A Form API array.
+   */
+  public static function settingsForm(&$field, &$instance);
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/SelectionPluginManager.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/SelectionPluginManager.php
new file mode 100644
index 0000000..7b9d1a2
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/Type/SelectionPluginManager.php
@@ -0,0 +1,84 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\Type\SelectionPluginManager.
+ */
+
+namespace Drupal\entity_reference\Plugin\Type;
+
+use Drupal\Component\Plugin\Exception\PluginException;
+use Drupal\Component\Plugin\Factory\ReflectionFactory;
+use Drupal\Component\Plugin\PluginManagerBase;
+use Drupal\Core\Plugin\Discovery\AlterDecorator;
+use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
+use Drupal\Core\Plugin\Discovery\CacheDecorator;
+use Drupal\entity_reference\Plugin\Type\Selection\SelectionBroken;
+
+/**
+ * Plugin type manager for the Entity Reference Selection plugin.
+ */
+class SelectionPluginManager extends PluginManagerBase {
+
+  /**
+   * Constructs a SelectionPluginManager object.
+   */
+  public function __construct() {
+    $this->baseDiscovery = new AlterDecorator(new AnnotatedClassDiscovery('entity_reference', 'selection'), 'entity_reference_selection');
+    $this->discovery = new CacheDecorator($this->baseDiscovery, 'entity_reference_selection');
+    $this->factory = new ReflectionFactory($this);
+  }
+
+  /**
+   * Overrides Drupal\Component\Plugin\PluginManagerBase::createInstace().
+   */
+  public function createInstance($plugin_id, array $configuration = array()) {
+    // We want to provide a broken handler class whenever a class is not found.
+    try {
+      return parent::createInstance($plugin_id, $configuration);
+    }
+    catch (PluginException $e) {
+      return new SelectionBroken($configuration['field'], $configuration['instance']);
+    }
+  }
+
+  /**
+   * Overrides Drupal\Component\Plugin\PluginManagerBase::getInstance().
+   */
+  public function getInstance(array $options) {
+    $selection_handler = $options['instance']['settings']['handler'];
+    $target_entity_type = $options['field']['settings']['target_type'];
+
+    // Get all available selection plugins for this entity type.
+    $selection_handler_groups = $this->getSelectionGroups($target_entity_type);
+
+    // Sort the selection plugins by weight and select the best match.
+    uasort($selection_handler_groups[$selection_handler], 'drupal_sort_weight');
+    end($selection_handler_groups[$selection_handler]);
+    $plugin_id = key($selection_handler_groups[$selection_handler]);
+
+    return $this->createInstance($plugin_id, $options);
+  }
+
+  /**
+   * Returns a list of selection plugins that can reference a specific entity
+   * type.
+   *
+   * @param string $entity_type
+   *   A Drupal entity type.
+   *
+   * @return array
+   *   An array of selection plugins grouped by selection group.
+   */
+  public function getSelectionGroups($entity_type) {
+    $plugins = array();
+
+    foreach ($this->getDefinitions() as $plugin_id => $plugin) {
+      if (!isset($plugin['entity_types']) || in_array($entity_type, $plugin['entity_types'])) {
+        $plugins[$plugin['group']][$plugin_id] = $plugin;
+      }
+    }
+
+    return $plugins;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php
new file mode 100644
index 0000000..9037fa6
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/entity_reference/selection/SelectionBase.php
@@ -0,0 +1,334 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase.
+ */
+
+namespace Drupal\entity_reference\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\AlterableInterface;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\Component\Utility\NestedArray;
+use Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface;
+
+/**
+ * Plugin implementation of the 'selection' entity_reference.
+ *
+ * @Plugin(
+ *   id = "base",
+ *   module = "entity_reference",
+ *   label = @Translation("Default"),
+ *   group = "base",
+ *   weight = 0,
+ *   derivative = "Drupal\entity_reference\Plugin\Derivative\SelectionBase"
+ * )
+ */
+class SelectionBase implements SelectionInterface {
+
+  /**
+   * The field array.
+   *
+   * @var array
+   */
+  protected $field;
+
+  /**
+   * The instance array.
+   *
+   * @var array
+   */
+  protected $instance;
+
+  /**
+   * The entity object, or NULL
+   *
+   * @var NULL|EntityInterface
+   */
+  protected $entity;
+
+  /**
+   * Constructs a SelectionBase object.
+   */
+  public function __construct($field, $instance, EntityInterface $entity = NULL) {
+    $this->field = $field;
+    $this->instance = $instance;
+    $this->entity = $entity;
+  }
+
+  /**
+   * Implements SelectionInterface::settingsForm().
+   */
+  public static function settingsForm(&$field, &$instance) {
+    $entity_info = entity_get_info($field['settings']['target_type']);
+
+    // Merge-in default values.
+    if (!isset($instance['settings']['handler_settings'])) {
+      $instance['settings']['handler_settings'] = array();
+    }
+    $instance['settings']['handler_settings'] += array(
+      'target_bundles' => array(),
+      'sort' => array(
+        'field' => '_none',
+      ),
+      'auto_create' => FALSE,
+    );
+
+    if (!empty($entity_info['entity_keys']['bundle'])) {
+      $bundles = array();
+      foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
+        $bundles[$bundle_name] = $bundle_info['label'];
+      }
+
+      $target_bundles_title = t('Bundles');
+      // Default core entity types with sensible labels.
+      if ($field['settings']['target_type'] == 'node') {
+        $target_bundles_title = t('Content types');
+      }
+      elseif ($field['settings']['target_type'] == 'taxonomy_term') {
+        $target_bundles_title = t('Vocabularies');
+      }
+
+      $form['target_bundles'] = array(
+        '#type' => 'checkboxes',
+        '#title' => $target_bundles_title,
+        '#options' => $bundles,
+        '#default_value' => (!empty($instance['settings']['handler_settings']['target_bundles'])) ? $instance['settings']['handler_settings']['target_bundles'] : array_keys($bundles),
+        '#size' => 6,
+        '#multiple' => TRUE,
+        '#description' => t('The bundles of the entity type that can be referenced.'),
+        '#element_validate' => array('_entity_reference_element_validate_filter'),
+      );
+    }
+    else {
+      $form['target_bundles'] = array(
+        '#type' => 'value',
+        '#value' => array(),
+      );
+    }
+
+    // @todo Use Entity::getPropertyDefinitions() when all entity types are
+    // converted to the new Field API.
+    $fields = drupal_map_assoc($entity_info['schema_fields_sql']['base_table']);
+    foreach (field_info_instances($field['settings']['target_type']) as $bundle_instances) {
+      foreach ($bundle_instances as $instance_name => $instance_info) {
+        $field_info = field_info_field($instance_name);
+        foreach ($field_info['columns'] as $column_name => $column_info) {
+          $fields[$instance_name . '.' . $column_name] = t('@label (@column)', array('@label' => $instance_info['label'], '@column' => $column_name));
+        }
+      }
+    }
+
+    $form['sort']['field'] = array(
+      '#type' => 'select',
+      '#title' => t('Sort by'),
+      '#options' => array(
+        '_none' => t('- None -'),
+      ) + $fields,
+      '#ajax' => TRUE,
+      '#limit_validation_errors' => array(),
+      '#default_value' => $instance['settings']['handler_settings']['sort']['field'],
+    );
+
+    $form['sort']['settings'] = array(
+      '#type' => 'container',
+      '#attributes' => array('class' => array('entity_reference-settings')),
+      '#process' => array('_entity_reference_form_process_merge_parent'),
+    );
+
+    if ($instance['settings']['handler_settings']['sort']['field'] != '_none') {
+      // Merge-in default values.
+      $instance['settings']['handler_settings']['sort'] += array(
+        'direction' => 'ASC',
+      );
+
+      $form['sort']['settings']['direction'] = array(
+        '#type' => 'select',
+        '#title' => t('Sort direction'),
+        '#required' => TRUE,
+        '#options' => array(
+          'ASC' => t('Ascending'),
+          'DESC' => t('Descending'),
+        ),
+        '#default_value' => $instance['settings']['handler_settings']['sort']['direction'],
+      );
+    }
+
+    $form['auto_create'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Auto-create'),
+      '#description' => t('Allow creating new entities in autocomplete.'),
+      '#default_value' => $instance['settings']['handler_settings']['auto_create'],
+    );
+
+    return $form;
+  }
+
+  /**
+   * Implements SelectionInterface::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    $target_type = $this->field['settings']['target_type'];
+
+    $query = $this->buildEntityQuery($match, $match_operator);
+    if ($limit > 0) {
+      $query->range(0, $limit);
+    }
+
+    $result = $query->execute();
+
+    if (empty($result)) {
+      return array();
+    }
+
+    $options = array();
+    $entities = entity_load_multiple($target_type, $result);
+    foreach ($entities as $entity_id => $entity) {
+      $bundle = $entity->bundle();
+      $options[$bundle][$entity_id] = check_plain($entity->label());
+    }
+
+    return $options;
+  }
+
+  /**
+   * Implements SelectionInterface::countReferencableEntities().
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    $query = $this->buildEntityQuery($match, $match_operator);
+    return $query
+      ->count()
+      ->execute();
+  }
+
+  /**
+   * Implements SelectionInterface::validateReferencableEntities().
+   */
+  public function validateReferencableEntities(array $ids) {
+    $result = array();
+    if ($ids) {
+      $target_type = $this->field['settings']['target_type'];
+      $entity_info = entity_get_info($target_type);
+      $query = $this->buildEntityQuery();
+      $result = $query
+        ->condition($entity_info['entity_keys']['id'], $ids, 'IN')
+        ->execute();
+    }
+
+    return $result;
+  }
+
+  /**
+   * Implements SelectionInterface::validateAutocompleteInput().
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE) {
+    $entities = $this->getReferencableEntities($input, '=', 6);
+    $params = array(
+      '%value' => $input,
+      '@value' => $input,
+    );
+    if (empty($entities)) {
+      if ($strict) {
+        // Error if there are no entities available for a required field.
+        form_error($element, t('There are no entities matching "%value".', $params));
+      }
+    }
+    elseif (count($entities) > 5) {
+      $params['@id'] = key($entities);
+      // Error if there are more than 5 matching entities.
+      form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)".', $params));
+    }
+    elseif (count($entities) > 1) {
+      // More helpful error if there are only a few matching entities.
+      $multiples = array();
+      foreach ($entities as $id => $name) {
+        $multiples[] = $name . ' (' . $id . ')';
+      }
+      $params['@id'] = $id;
+      form_error($element, t('Multiple entities match this reference; "%multiple". Specify the one you want by appending the id in parentheses, like "@value (@id)".', array('%multiple' => implode('", "', $multiples))));
+    }
+    else {
+      // Take the one and only matching entity.
+      return key($entities);
+    }
+  }
+
+  /**
+   * Builds an EntityQuery to get referencable entities.
+   *
+   * @param string|null $match
+   *   (Optional) Text to match the label against. Defaults to NULL.
+   * @param string $match_operator
+   *   (Optional) The operation the matching should be done with. Defaults
+   *   to "CONTAINS".
+   *
+   * @return \Drupal\Core\Entity\Query\QueryInterface
+   *   The EntityQuery object with the basic conditions and sorting applied to
+   *   it.
+   */
+  public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $target_type = $this->field['settings']['target_type'];
+    $entity_info = entity_get_info($target_type);
+
+    $query = entity_query($target_type);
+    if (!empty($this->instance['settings']['handler_settings']['target_bundles'])) {
+      // @todo: Taxonomy term's bundle key is vocabulary_machine_name, but
+      // entity_query() fails with it, so for now hardcode the vid, until
+      // http://drupal.org/node/1552396 is fixed.
+      $bundle_key = $target_type != 'taxonomy_term' ? $entity_info['entity_keys']['bundle'] : 'vid';
+      $query->condition($bundle_key, $this->instance['settings']['handler_settings']['target_bundles'], 'IN');
+    }
+
+    if (isset($match) && isset($entity_info['entity_keys']['label'])) {
+      $query->condition($entity_info['entity_keys']['label'], $match, $match_operator);
+    }
+
+    // Add entity-access tag.
+    $query->addTag($this->field['settings']['target_type'] . '_access');
+
+    // Add the Selection handler for
+    // entity_reference_query_entity_reference_alter()
+    $query->addTag('entity_reference');
+    $query->addMetaData('field', $this->field);
+    $query->addMetaData('entity_reference_selection_handler', $this);
+
+    // Add the sort option.
+    if (!empty($this->instance['settings']['handler_settings']['sort'])) {
+      $sort_settings = $this->instance['settings']['handler_settings']['sort'];
+      if ($sort_settings['field'] != '_none') {
+        $query->sort($sort_settings['field'], $sort_settings['direction']);
+      }
+    }
+
+    return $query;
+  }
+
+  /**
+   * Implements SelectionInterface::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) { }
+
+  /**
+   * Helper method: Passes a query to the alteration system again.
+   *
+   * This allows Entity Reference to add a tag to an existing query so it can
+   * ask access control mechanisms to alter it again.
+   */
+  protected function reAlterQuery(AlterableInterface $query, $tag, $base_table) {
+    // Save the old tags and metadata.
+    // For some reason, those are public.
+    $old_tags = $query->alterTags;
+    $old_metadata = $query->alterMetaData;
+
+    $query->alterTags = array($tag => TRUE);
+    $query->alterMetaData['base_table'] = $base_table;
+    drupal_alter(array('query', 'query_' . $tag), $query);
+
+    // Restore the tags and metadata.
+    $query->alterTags = $old_tags;
+    $query->alterMetaData = $old_metadata;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
new file mode 100644
index 0000000..ecf3e6f
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceEntityFormatter.php
@@ -0,0 +1,119 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\formatter\EntityReferenceEntityFormatter.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entity_reference\RecursiveRenderingException;
+use Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference rendered entity' formatter.
+ *
+ * @Plugin(
+ *   id = "entity_reference_entity_view",
+ *   module = "entity_reference",
+ *   label = @Translation("Rendered entity"),
+ *   description = @Translation("Display the referenced entities rendered by entity_view()."),
+ *   field_types = {
+ *     "entity_reference"
+ *   },
+ *   settings = {
+ *     "view_mode" = "",
+ *     "link" = FALSE
+ *   }
+ * )
+ */
+class EntityReferenceEntityFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+    $entity_info = entity_get_info($this->field['settings']['target_type']);
+    $options = array();
+    if (!empty($entity_info['view modes'])) {
+      foreach ($entity_info['view modes'] as $view_mode => $view_mode_settings) {
+        $options[$view_mode] = $view_mode_settings['label'];
+      }
+    }
+
+    $elements['view_mode'] = array(
+      '#type' => 'select',
+      '#options' => $options,
+      '#title' => t('View mode'),
+      '#default_value' => $this->getSetting('view_mode'),
+      '#required' => TRUE,
+    );
+
+    $elements['links'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Show links'),
+      '#default_value' => $this->getSetting('links'),
+    );
+
+    return $elements;
+  }
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary().
+   */
+  public function settingsSummary() {
+    $summary = array();
+
+    $entity_info = entity_get_info($this->field['settings']['target_type']);
+    $view_mode = $this->getSetting('view_mode');
+    $summary[] = t('Rendered as @mode', array('@mode' => isset($entity_info['view modes'][$view_mode]['label']) ? $entity_info['view modes'][$view_mode]['label'] : $view_mode));
+    $summary[] = $this->getSetting('links') ? t('Display links') : t('Do not display links');
+
+    return implode('<br />', $summary);
+  }
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove un-accessible items.
+    parent::viewElements($entity, $langcode, $items);
+
+    $view_mode = $this->getSetting('view_mode');
+    $links = $this->getSetting('links');
+
+    $target_type = $this->field['settings']['target_type'];
+
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      // Protect ourselves from recursive rendering.
+      static $depth = 0;
+      $depth++;
+      if ($depth > 20) {
+        throw new RecursiveRenderingException(format_string('Recursive rendering detected when rendering entity @entity_type(@entity_id). Aborting rendering.', array('@entity_type' => $entity_type, '@entity_id' => $item['target_id'])));
+      }
+
+      if (!empty($item['entity'])) {
+        $entity = clone $item['entity'];
+        unset($entity->content);
+        $elements[$delta] = entity_view($entity, $view_mode, $langcode);
+
+        if (empty($links) && isset($result[$delta][$target_type][$item['target_id']]['links'])) {
+          // Hide the element links.
+          $elements[$delta][$target_type][$item['target_id']]['links']['#access'] = FALSE;
+        }
+      }
+      else {
+        // This is an "auto_create" item.
+        $elements[$delta] = array('#markup' => $item['label']);
+      }
+      $depth = 0;
+    }
+
+    return $elements;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
new file mode 100644
index 0000000..ed8dc2e
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceFormatterBase.php
@@ -0,0 +1,118 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\field\Plugin\Type\Formatter\FormatterBase;
+
+/**
+ * Parent plugin for entity-reference formatters.
+ */
+abstract class EntityReferenceFormatterBase extends FormatterBase {
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::prepareView().
+   *
+   * Mark the accessible IDs a user can see. We do not unset unaccessible
+   * values, as other may want to act on those values, even if they can
+   * not be accessed.
+   */
+  public function prepareView(array $entities, $langcode, array &$items) {
+    $target_ids = array();
+    $revision_ids = array();
+
+    // Collect every possible entity attached to any of the entities.
+    foreach ($entities as $id => $entity) {
+      foreach ($items[$id] as $delta => $item) {
+        if (!empty($item['revision_id'])) {
+          $revision_ids[] = $item['revision_id'];
+        }
+        elseif (!empty($item['target_id'])) {
+          $target_ids[] = $item['target_id'];
+        }
+      }
+    }
+
+    $target_type = $this->field['settings']['target_type'];
+
+    $target_entities = array();
+
+    if ($target_ids) {
+      $target_entities = entity_load_multiple($target_type, $target_ids);
+    }
+
+    if ($revision_ids) {
+      // We need to load the revisions one by-one.
+      foreach ($revision_ids as $revision_id) {
+        $entity = entity_revision_load($target_type, $revision_id);
+        // Use the revision-ID in the key.
+        $identifier = $entity->id() . ':' . $revision_id;
+        $target_entities[$identifier] = $entity;
+      }
+    }
+
+    // Iterate through the fieldable entities again to attach the loaded
+    // data.
+    foreach ($entities as $id => $entity) {
+      $rekey = FALSE;
+      foreach ($items[$id] as $delta => $item) {
+        // If we have a revision-ID, the key uses it as-well.
+        $identifier = !empty($item['revision_id']) ? $item['target_id'] . ':' . $item['revision_id'] : $item['target_id'];
+        if ($item['target_id'] != 'auto_create') {
+          if (!isset($target_entities[$identifier])) {
+            // The entity no longer exists, so remove the key.
+            $rekey = TRUE;
+            unset($items[$id][$delta]);
+            continue;
+          }
+
+          $entity = $target_entities[$identifier];
+          $items[$id][$delta]['entity'] = $entity;
+
+          // @todo: Improve when we have entity_access().
+          $entity_access = $target_type == 'node' ? node_access('view', $entity) : TRUE;
+          if (!$entity_access) {
+            continue;
+          }
+        }
+        else {
+          // This is an "auto_create" item, so allow access to it, as the entity doesn't
+          // exists yet, and we are probably in a preview.
+          $items[$id][$delta]['entity'] = FALSE;
+          // Add the label as a special key, as we cannot use entity_label().
+          $items[$id][$delta]['label'] = $item['label'];
+        }
+
+        // Mark item as accessible.
+        $items[$id][$delta]['access'] = TRUE;
+      }
+
+      if ($rekey) {
+        // Rekey the items array.
+        $items[$id] = array_values($items[$id]);
+      }
+    }
+  }
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::viewElements().
+   *
+   * @see Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove un-accessible items.
+    foreach ($items as $delta => $item) {
+      if (empty($item['access'])) {
+        unset($items[$delta]);
+      }
+    }
+    return array();
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
new file mode 100644
index 0000000..263a24e
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceIdFormatter.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\formatter\EntityReferenceIdFormatter.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference ID' formatter.
+ *
+ * @Plugin(
+ *   id = "entity_reference_entity_id",
+ *   module = "entity_reference",
+ *   label = @Translation("Entity ID"),
+ *   description = @Translation("Display the ID of the referenced entities."),
+ *   field_types = {
+ *     "entity_reference"
+ *   }
+ * )
+ */
+class EntityReferenceIdFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      if (!empty($item['entity'])) {
+        $elements[$delta] = array('#markup' => check_plain($item['target_id']));
+      }
+    }
+
+    return $elements;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
new file mode 100644
index 0000000..dce40e2
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/formatter/EntityReferenceLabelFormatter.php
@@ -0,0 +1,90 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\formatter\EntityReferenceLabelFormatter.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference label' formatter.
+ *
+ * @Plugin(
+ *   id = "entity_reference_label",
+ *   module = "entity_reference",
+ *   label = @Translation("Label"),
+ *   description = @Translation("Display the label of the referenced entities."),
+ *   field_types = {
+ *     "entity_reference"
+ *   },
+ *   settings = {
+ *     "link" = FALSE
+ *   }
+ * )
+ */
+class EntityReferenceLabelFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+    $elements['link'] = array(
+      '#title' => t('Link label to the referenced entity'),
+      '#type' => 'checkbox',
+      '#default_value' => $this->getSetting('link'),
+    );
+
+    return $elements;
+  }
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Formatter\FormatterBase::settingsSummary().
+   */
+  public function settingsSummary() {
+    $summary = array();
+    $summary[] = $this->getSetting('link') ? t('Link to the referenced entity') : t('No link');
+
+    return implode('<br />', $summary);
+  }
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    // Remove un-accessible items.
+    parent::viewElements($entity, $langcode, $items);
+
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      if ($entity = $item['entity']) {
+        $label = $entity->label();
+        // If the link is to be displayed and the entity has a uri,
+        // display a link.
+        if ($this->getSetting('link') && $uri = $entity->uri()) {
+          $elements[$delta] = array(
+            '#type' => 'link',
+            '#title' => $label,
+            '#href' => $uri['path'],
+            '#options' => $uri['options'],
+          );
+        }
+        else {
+          $elements[$delta] = array('#markup' => check_plain($label));
+        }
+      }
+      else {
+        // This is an "auto_create" item.
+        $elements[$delta] = array('#markup' => $item['label']);
+      }
+    }
+
+    return $elements;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
new file mode 100644
index 0000000..c19b8a6
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteTagsWidget.php
@@ -0,0 +1,80 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\widget\AutocompleteTagsWidget.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase;
+
+/**
+ * Plugin implementation of the 'entity_reference autocomplete-tags' widget.
+ *
+ * @Plugin(
+ *   id = "entity_reference_autocomplete_tags",
+ *   module = "entity_reference",
+ *   label = @Translation("Autocomplete (Tags style)"),
+ *   description = @Translation("An autocomplete text field."),
+ *   field_types = {
+ *     "entity_reference"
+ *   },
+ *   settings = {
+ *     "match_operator" = "CONTAINS",
+ *     "size" = 60,
+ *     "autocomplete_path" = "entity_reference/autocomplete/tags",
+ *     "placeholder" = ""
+ *   },
+ *   multiple_values = FIELD_BEHAVIOR_CUSTOM
+ * )
+ */
+class AutocompleteTagsWidget extends AutocompleteWidgetBase {
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    return $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state);
+  }
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()
+   */
+  public function elementValidate($element, &$form_state, $form) {
+    $value = array();
+    // If a value was entered into the autocomplete.
+    $handler = entity_reference_get_selection_handler($this->field, $this->instance);
+    $entity_info = entity_get_info($this->field['settings']['target_type']);
+    $auto_create = isset($this->instance['settings']['handler_settings']['auto_create']) ? $this->instance['settings']['handler_settings']['auto_create'] : FALSE;
+
+    if (!empty($element['#value'])) {
+      $entities = drupal_explode_tags($element['#value']);
+      $value = array();
+      foreach ($entities as $entity) {
+        $match = FALSE;
+
+        // Take "label (entity id)', match the id from parenthesis.
+        if (preg_match("/.+\((\d+)\)/", $entity, $matches)) {
+          $match = $matches[1];
+        }
+        else {
+          // Try to get a match from the input string when the user didn't use the
+          // autocomplete but filled in a value manually.
+          $match = $handler->validateAutocompleteInput($entity, $element, $form_state, $form, !$auto_create);
+        }
+
+        if ($match) {
+          $value[] = array('target_id' => $match);
+        }
+        elseif ($auto_create && (count($this->instance['settings']['handler_settings']['target_bundles']) == 1 || count($entity_info['bundles']) == 1)) {
+          // Auto-create item. see entity_reference_field_presave().
+          $value[] = array('target_id' => 'auto_create', 'label' => $entity);
+        }
+      }
+    }
+    form_set_value($element, $value, $form_state);
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
new file mode 100644
index 0000000..2663bdb
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidget.php
@@ -0,0 +1,92 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\widget\AutocompleteWidget.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase;
+
+/**
+ * Plugin implementation of the 'entity_reference autocomplete' widget.
+ *
+ * @todo: Check if the following statement is still correct
+ * The autocomplete path doesn't have a default here, because it's not the
+ * the two widgets, and the Field API doesn't update default settings when
+ * the widget changes.
+ *
+ * @Plugin(
+ *   id = "entity_reference_autocomplete",
+ *   module = "entity_reference",
+ *   label = @Translation("Autocomplete"),
+ *   description = @Translation("An autocomplete text field."),
+ *   field_types = {
+ *     "entity_reference"
+ *   },
+ *   settings = {
+ *     "match_operator" = "CONTAINS",
+ *     "size" = 60,
+ *     "autocomplete_path" = "entity_reference/autocomplete/single",
+ *     "placeholder" = ""
+ *   }
+ * )
+ */
+class AutocompleteWidget extends AutocompleteWidgetBase {
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    // We let the Field API handles multiple values for us, only take care of
+    // the one matching our delta.
+    if (isset($items[$delta])) {
+      $items = array($items[$delta]);
+    }
+    else {
+      $items = array();
+    }
+
+    $element = $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state);
+    return array('target_id' => $element);
+  }
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase::elementValidate()
+   */
+  public function elementValidate($element, &$form_state, $form) {
+    $auto_create = isset($this->instance['settings']['handler_settings']['auto_create']) ? $this->instance['settings']['handler_settings']['auto_create'] : FALSE;
+
+    // If a value was entered into the autocomplete.
+    $value = '';
+    if (!empty($element['#value'])) {
+      // Take "label (entity id)', match the id from parenthesis.
+      if (preg_match("/.+\((\d+)\)/", $element['#value'], $matches)) {
+        $value = $matches[1];
+      }
+      else {
+        // Try to get a match from the input string when the user didn't use the
+        // autocomplete but filled in a value manually.
+        $handler = entity_reference_get_selection_handler($this->field, $this->instance);
+        $value = $handler->validateAutocompleteInput($element['#value'], $element, $form_state, $form, !$auto_create);
+      }
+
+      if (!$value && $auto_create && (count($this->instance['settings']['handler_settings']['target_bundles']) == 1 || count($entity_info['bundles']) == 1)) {
+        // Auto-create item. see entity_reference_field_presave().
+        $value = array(
+          'target_id' => 'auto_create',
+          'label' => $element['#value'],
+          // Keep the weight property.
+          '_weight' => $element['#weight'],
+        );
+        // Change the element['#parents'], so in form_set_value() we
+        // populate the correct key.
+        array_pop($element['#parents']);
+      }
+    }
+    form_set_value($element, $value, $form_state);
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
new file mode 100644
index 0000000..5ffd0f9
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/field/widget/AutocompleteWidgetBase.php
@@ -0,0 +1,132 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\field\widget\AutocompleteWidgetBase.
+ */
+
+namespace Drupal\entity_reference\Plugin\field\widget;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\field\Plugin\Type\Widget\WidgetBase;
+
+/**
+ * Parent plugin for entity-reference autocomplete widgets.
+ */
+abstract class AutocompleteWidgetBase extends WidgetBase {
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Widget\WidgetBase::settingsForm().
+   */
+  public function settingsForm(array $form, array &$form_state) {
+    $element['match_operator'] = array(
+      '#type' => 'select',
+      '#title' => t('Autocomplete matching'),
+      '#default_value' => $this->getSetting('match_operator'),
+      '#options' => array(
+        'STARTS_WITH' => t('Starts with'),
+        'CONTAINS' => t('Contains'),
+      ),
+      '#description' => t('Select the method used to collect autocomplete suggestions. Note that <em>Contains</em> can cause performance issues on sites with thousands of nodes.'),
+    );
+    $element['size'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Size of textfield'),
+      '#default_value' => $this->getSetting('size'),
+      '#element_validate' => array('form_validate_number'),
+      // Minimum value for form_validate_number().
+      '#min' => 1,
+      '#required' => TRUE,
+    );
+
+    $element['placeholder'] = array(
+      '#type' => 'textfield',
+      '#title' => t('Placeholder'),
+      '#default_value' => $this->getSetting('placeholder'),
+      '#description' => t('The placeholder is a short hint (a word or short phrase) intended to aid the user with data entry. A hint could be a sample value or a brief description of the expected format.'),
+    );
+
+
+    return $element;
+  }
+
+  /**
+   * Implements Drupal\field\Plugin\Type\Widget\WidgetInterface::formElement().
+   */
+  public function formElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    $element = $this->prepareElement($items, $delta, $element, $langcode, $form, $form_state, 'entity_reference/autocomplete/single');
+    return array('target_id' => $element);
+  }
+
+  /**
+   * Prepares the element.
+   */
+  protected function prepareElement(array $items, $delta, array $element, $langcode, array &$form, array &$form_state) {
+    $instance = $this->instance;
+    $field = $this->field;
+    $entity = isset($element['#entity']) ? $element['#entity'] : NULL;
+
+    // Prepare the autocomplete path.
+    $autocomplete_path = $this->getSetting('autocomplete_path');
+    $autocomplete_path .= '/' . $field['field_name'] . '/' . $instance['entity_type'] . '/' . $instance['bundle'] . '/';
+
+    // Use <NULL> as a placeholder in the URL when we don't have an entity.
+    // Most webservers collapse two consecutive slashes.
+    $id = 'NULL';
+    if ($entity && $entity_id = $entity->id()) {
+      $id = $entity_id;
+    }
+    $autocomplete_path .= $id;
+
+    $element += array(
+      '#type' => 'textfield',
+      '#maxlength' => 1024,
+      '#default_value' => implode(', ', $this->getLabels($items)),
+      '#autocomplete_path' => $autocomplete_path,
+      '#size' => $this->getSetting('size'),
+      '#placeholder' => $this->getSetting('placeholder'),
+      '#element_validate' => array(array($this, 'elementValidate')),
+    );
+    return $element;
+  }
+
+  /**
+   * Overrides Drupal\field\Plugin\Type\Widget\WidgetBase::errorElement().
+   */
+  public function errorElement(array $element, array $error, array $form, array &$form_state) {
+    return $element['target_id'];
+  }
+
+  /**
+   * Validates an element.
+   */
+  public function elementValidate($element, &$form_state, $form) { }
+
+  /**
+   * Gets the entity labels.
+   */
+  protected function getLabels(array $items) {
+    $entity_ids = array();
+    $entity_labels = array();
+
+    // Build an array of entities ID.
+    foreach ($items as $item) {
+      $entity_ids[] = $item['target_id'];
+    }
+
+    // Load those entities and loop through them to extract their labels.
+    $entities = entity_load_multiple($this->field['settings']['target_type'], $entity_ids);
+
+    foreach ($entities as $entity_id => $entity_item) {
+      $label = $entity_item->label();
+      $key = "$label ($entity_id)";
+      // Labels containing commas or quotes must be wrapped in quotes.
+      if (strpos($key, ',') !== FALSE || strpos($key, '"') !== FALSE) {
+        $key = '"' . str_replace('"', '""', $key) . '"';
+      }
+      $entity_labels[] = $key;
+    }
+    return $entity_labels;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
new file mode 100644
index 0000000..9327aa5
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/display/EntityReference.php
@@ -0,0 +1,183 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\views\display\EntityReference.
+ */
+
+namespace Drupal\entity_reference\Plugin\views\display;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\views\Plugin\views\display\DisplayPluginBase;
+
+/**
+ * The plugin that handles an EntityReference display.
+ *
+ * "entity_reference_display" is a custom property, used with
+ * views_get_applicable_views() to retrieve all views with a
+ * 'Entity Reference' display.
+ *
+ * @ingroup views_display_plugins
+ *
+ * @Plugin(
+ *   id = "entity_reference",
+ *   title = @Translation("EntityReference"),
+ *   admin = @Translation("Entity Reference Source"),
+ *   help = @Translation("Selects referenceable entities for an entity reference field."),
+ *   theme = "views_view",
+ *   uses_hook_menu = FALSE,
+ *  entity_reference_display = TRUE
+ * )
+ */
+class EntityReference extends DisplayPluginBase {
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::$useAJAX.
+   */
+  protected $usesAJAX = FALSE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::$usesPager.
+   */
+  protected $usesPager = FALSE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::$usesAttachments.
+   */
+  protected $usesAttachments = FALSE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::defineOptions().
+   */
+  protected function defineOptions() {
+    $options = parent::defineOptions();
+
+    // Force the style plugin to 'entity_reference_style' and the row plugin to
+    // 'fields'.
+    $options['style']['contains']['type'] = array('default' => 'entity_reference');
+    $options['defaults']['default']['style'] = FALSE;
+    $options['row']['contains']['type'] = array('default' => 'entity_reference');
+    $options['defaults']['default']['row'] = FALSE;
+
+    // Make sure the query is not cached.
+    $options['defaults']['default']['cache'] = FALSE;
+
+    // Set the display title to an empty string (not used in this display type).
+    $options['title']['default'] = '';
+    $options['defaults']['default']['title'] = FALSE;
+
+    return $options;
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::optionsSummary().
+   *
+   * Disable 'cache' and 'title' so it won't be changed.
+   */
+  public function optionsSummary(&$categories, &$options) {
+    parent::optionsSummary($categories, $options);
+    unset($options['query']);
+    unset($options['title']);
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::getStyleType().
+   */
+  protected function getStyleType() {
+    return 'entity_reference';
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::execute().
+   */
+  public function execute() {
+    return $this->view->render($this->display['id']);
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::render().
+   */
+  public function render() {
+    if (!empty($this->view->result) && $this->view->style_plugin->even_empty()) {
+      return $this->view->style_plugin->render($this->view->result);
+    }
+    return '';
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::usesExposed().
+   */
+  public function usesExposed() {
+    return FALSE;
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::query().
+   */
+  public function query() {
+    if (!empty($this->view->live_preview)) {
+      return;
+    }
+
+    // Make sure the id field is included in the results.
+    $id_field = $this->view->storage->get('base_field');
+    $this->id_field_alias = $this->view->query->add_field($this->view->storage->get('base_table'), $id_field);
+
+    $options = $this->getOption('entity_reference_options');
+
+    // Restrict the autocomplete options based on what's been typed already.
+    if (isset($options['match'])) {
+      $style_options = $this->getOption('style');
+      $value = db_like($options['match']) . '%';
+      if ($options['match_operator'] != 'STARTS_WITH') {
+        $value = '%' . $value;
+      }
+
+      // Multiple search fields are OR'd together
+      $conditions = db_or();
+
+      // Build the condition using the selected search fields
+      foreach ($style_options['options']['search_fields'] as $field_alias) {
+        if (!empty($field_alias)) {
+          // Get the table and field names for the checked field
+          $field = $this->view->query->fields[$this->view->field[$field_alias]->field_alias];
+          // Add an OR condition for the field
+          $conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE');
+        }
+      }
+
+      $this->view->query->add_where(0, $conditions);
+    }
+
+    // Add an IN condition for validation.
+    if (!empty($options['ids'])) {
+      $this->view->query->add_where(0, $id_field, $options['ids']);
+    }
+
+    $this->view->setItemsPerPage($options['limit']);
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\DisplayPluginBase::validate().
+   */
+  public function validate() {
+    $errors = parent::validate();
+    // Verify that search fields are set up.
+    $style = $this->getOption('style');
+    if (!isset($style['options']['search_fields'])) {
+      $errors[] = t('Display "@display" needs a selected search fields to work properly. See the settings for the Entity Reference list format.', array('@display' => $this->display['display_title']));
+    }
+    else {
+      // Verify that the search fields used actually exist.
+      //$fields = array_keys($this->view->get_items('field'));
+      $fields = array_keys($this->handlers['field']);
+      foreach ($style['options']['search_fields'] as $field_alias => $enabled) {
+        if ($enabled && !in_array($field_alias, $fields)) {
+          $errors[] = t('Display "@display" uses field %field as search field, but the field is no longer present. See the settings for the Entity Reference list format.', array('@display' => $this->display['display_title'], '%field' => $field_alias));
+        }
+      }
+    }
+    return $errors;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php
new file mode 100644
index 0000000..7e3a970
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/row/EntityReference.php
@@ -0,0 +1,61 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\views\row\EntityReference.
+ */
+
+namespace Drupal\entity_reference\Plugin\views\row;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\views\Plugin\views\row\Fields;
+
+/**
+ * EntityReference row plugin.
+ *
+ * @ingroup views_row_plugins
+ *
+ * @Plugin(
+ *   id = "entity_reference",
+ *   title = @Translation("Entity Reference inline fields"),
+ *   help = @Translation("Displays the fields with an optional template."),
+ *   theme = "views_view_fields",
+ *   type = "entity_reference"
+ * )
+ */
+class EntityReference extends Fields {
+
+  /**
+   * Overrides Drupal\views\Plugin\views\row\Fields::defineOptions().
+   */
+  protected function defineOptions() {
+    $options = parent::defineOptions();
+    $options['separator'] = array('default' => '-');
+
+    return $options;
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\row\Fields::buildOptionsForm().
+   */
+  public function buildOptionsForm(&$form, &$form_state) {
+    parent::buildOptionsForm($form, $form_state);
+
+    // Expand the description of the 'Inline field' checkboxes.
+    $form['inline']['#description'] .= '<br />' . t("<strong>Note:</strong> In 'Entity Reference' displays, all fields will be displayed inline unless an explicit selection of inline fields is made here." );
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\row\Fields::pre_render().
+   */
+  public function pre_render($row) {
+    // Force all fields to be inline by default.
+    if (empty($this->options['inline'])) {
+      $fields = $this->view->getItems('field', $this->displayHandler->display['id']);
+      $this->options['inline'] = drupal_map_assoc(array_keys($fields));
+    }
+
+    return parent::pre_render($row);
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
new file mode 100644
index 0000000..c15c2ae
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Plugin/views/style/EntityReference.php
@@ -0,0 +1,120 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Plugin\views\style\EntityReference.
+ */
+
+namespace Drupal\entity_reference\Plugin\views\style;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\views\Plugin\views\style\StylePluginBase;
+
+/**
+ * EntityReference style plugin.
+ *
+ * @ingroup views_style_plugins
+ *
+ * @Plugin(
+ *   id = "entity_reference",
+ *   title = @Translation("Entity Reference list"),
+ *   help = @Translation("Returns results as a PHP array of labels and rendered rows."),
+ *   theme = "views_view_unformatted",
+ *   type = "entity_reference"
+ * )
+ */
+class EntityReference extends StylePluginBase {
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase::usesRowPlugin.
+   */
+  protected $usesRowPlugin = TRUE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase::usesFields.
+   */
+  protected $usesFields = TRUE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase::usesGrouping.
+   */
+  protected $usesGrouping = FALSE;
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::defineOptions().
+   */
+  protected function defineOptions() {
+    $options = parent::defineOptions();
+    $options['search_fields'] = array('default' => NULL);
+
+    return $options;
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::buildOptionsForm().
+   */
+  public function buildOptionsForm(&$form, &$form_state) {
+    parent::buildOptionsForm($form, $form_state);
+
+    $options = $this->displayHandler->getFieldLabels(TRUE);
+    $form['search_fields'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Search fields'),
+      '#options' => $options,
+      '#required' => TRUE,
+      '#default_value' => $this->options['search_fields'],
+      '#description' => t('Select the field(s) that will be searched when using the autocomplete widget.'),
+      '#weight' => -3,
+    );
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::render().
+   */
+  public function render() {
+    if (!empty($this->view->live_preview)) {
+      return parent::render();
+    }
+
+    // Group the rows according to the grouping field, if specified.
+    $sets = $this->render_grouping($this->view->result, $this->options['grouping']);
+
+    // Grab the alias of the 'id' field added by entity_reference_plugin_display.
+    $id_field_alias = $this->view->storage->get('base_field');
+
+    // @todo We don't display grouping info for now. Could be useful for select
+    // widget, though.
+    $results = array();
+    $this->view->row_index = 0;
+    foreach ($sets as $records) {
+      foreach ($records as $values) {
+        // Sanitize html, remove line breaks and extra whitespace.
+        $output = $this->row_plugin->render($values);
+        $output = drupal_render($output);
+        $results[$values->{$id_field_alias}] = filter_xss_admin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $output)));
+        $this->view->row_index++;
+      }
+    }
+    unset($this->view->row_index);
+    return $results;
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\display\PathPluginBase::preview().
+   */
+  public function preview() {
+    if (!empty($this->view->live_preview)) {
+      return '<pre>' . check_plain($this->view->render()) . '</pre>';
+    }
+
+    return $this->view->render();
+  }
+
+  /**
+   * Overrides Drupal\views\Plugin\views\style\StylePluginBase\StylePluginBase::even_empty().
+   */
+  function even_empty() {
+    return TRUE;
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php b/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php
new file mode 100644
index 0000000..e0fce9c
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/RecursiveRenderingException.php
@@ -0,0 +1,14 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\RecursiveRenderingException.
+ */
+
+namespace Drupal\entity_reference;
+
+/**
+ * Exception thrown when the entity view renderer goes into a potentially
+ * infinite loop.
+ */
+class RecursiveRenderingException extends \Exception {}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php
new file mode 100644
index 0000000..437e0ae
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAdminTest.php
@@ -0,0 +1,108 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceAdminTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference Admin UI.
+ */
+class EntityReferenceAdminTest extends WebTestBase {
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference UI',
+      'description' => 'Tests for the administrative UI.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('field_ui', 'entity_reference');
+
+  public function setUp() {
+    parent::setUp();
+
+    // Create test user.
+    $this->admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));
+    $this->drupalLogin($this->admin_user);
+
+    // Create content type, with underscores.
+    $type_name = strtolower($this->randomName(8)) . '_test';
+    $type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
+    $this->type = $type->type;
+  }
+
+  protected function assertFieldSelectOptions($name, $expected_options) {
+    $xpath = $this->buildXPathQuery('//select[@name=:name]', array(':name' => $name));
+    $fields = $this->xpath($xpath);
+    if ($fields) {
+      $field = $fields[0];
+      $options = $this->getAllOptionsList($field);
+      return $this->assertIdentical($options, $expected_options);
+    }
+    else {
+      return $this->fail(t('Unable to find field @name', array('@name' => $name)));
+    }
+  }
+
+  /**
+   * Extract all the options of a select element.
+   */
+  protected function getAllOptionsList($element) {
+    $options = array();
+    // Add all options items.
+    foreach ($element->option as $option) {
+      $options[] = (string) $option['value'];
+    }
+    // TODO: support optgroup.
+    return $options;
+  }
+
+  public function testFieldAdminHandler() {
+    $bundle_path = 'admin/structure/types/manage/' . $this->type;
+
+    // First step: 'Add new field' on the 'Manage fields' page.
+    $this->drupalPost($bundle_path . '/fields', array(
+      'fields[_add_new_field][label]' => 'Test label',
+      'fields[_add_new_field][field_name]' => 'test',
+      'fields[_add_new_field][type]' => 'entity_reference',
+      'fields[_add_new_field][widget_type]' => 'entity_reference_autocomplete',
+    ), t('Save'));
+
+    // Node should be selected by default.
+    $this->assertFieldByName('field[settings][target_type]', 'node');
+
+    // Second step: 'Instance settings' form.
+    $this->drupalPost(NULL, array(), t('Save field settings'));
+
+    // The base handler should be selected by default.
+    $this->assertFieldByName('instance[settings][handler]', 'base');
+
+    // The base handler settings should be displayed.
+    $entity_type = 'node';
+    $entity_info = entity_get_info($entity_type);
+    foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
+      $this->assertFieldByName('instance[settings][handler_settings][target_bundles][' . $bundle_name . ']');
+    }
+
+    // Test the sort settings.
+    // Option 0: no sort.
+    $this->assertFieldByName('instance[settings][handler_settings][sort][field]', '_none');
+    $this->assertNoFieldByName('instance[settings][handler_settings][sort][direction]');
+    // Option 1: sort by field.
+    $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][field]' => 'nid'), 'instance[settings][handler_settings][sort][field]');
+    $this->assertFieldByName('instance[settings][handler_settings][sort][direction]', 'ASC');
+    // Set back to no sort.
+    $this->drupalPostAJAX(NULL, array('instance[settings][handler_settings][sort][field]' => '_none'), 'instance[settings][handler_settings][sort][field]');
+
+    // Third step: confirm.
+    $this->drupalPost(NULL, array(), t('Save settings'));
+
+    // Check that the field appears in the overview form.
+    $this->assertFieldByXPath('//table[@id="field-overview"]//td[1]', 'Test label', t('Field was created and appears in the overview page.'));
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php
new file mode 100644
index 0000000..7ed83c2
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutoCreateTest.php
@@ -0,0 +1,111 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceAutoCreateTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference auto-creation feature.
+ */
+class EntityReferenceAutoCreateTest extends WebTestBase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference auto-create',
+      'description' => 'Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('entity_reference', 'node');
+
+  function setUp() {
+    parent::setUp();
+
+    // Create a "referecning" and "referenced" node types.
+    $referencing = $this->drupalCreateContentType();
+    $this->referencing_type = $referencing->type;
+
+    $referenced = $this->drupalCreateContentType();
+    $this->referenced_type = $referenced->type;
+
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+    );
+
+    field_create_field($field);
+
+    $instance = array(
+      'label' => 'Entity reference field',
+      'field_name' => 'test_field',
+      'entity_type' => 'node',
+      'bundle' => $referencing->type,
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          // Reference a single vocabulary.
+          'target_bundles' => array(
+            $referenced->type,
+          ),
+          // Enable auto-create.
+          'auto_create' => TRUE,
+        ),
+      ),
+    );
+
+    field_create_instance($instance);
+  }
+
+  /**
+   * Assert creation on a new entity.
+   */
+  public function testAutoCreate() {
+    $user1 = $this->drupalCreateUser(array('access content', "create $this->referencing_type content"));
+    $this->drupalLogin($user1);
+
+    $new_title = $this->randomName();
+
+    // Assert referenced node does not exist.
+    $base_query = entity_query('node');
+    $base_query
+      ->condition('type', $this->referenced_type)
+      ->condition('title', $new_title);
+
+    $query = clone $base_query;
+    $result = $query->execute();
+    $this->assertFalse($result, 'Referenced node does not exist yet.');
+
+    $edit = array(
+      'title' => $this->randomName(),
+      'test_field[und][0][target_id]' => $new_title,
+    );
+    $this->drupalPost("node/add/$this->referencing_type", $edit, 'Save');
+
+    // Assert referenced node was created.
+    $query = clone $base_query;
+    $result = $query->execute();
+    $this->assertTrue($result, 'Referenced node was created.');
+    $referenced_nid = key($result);
+
+    // Assert the referenced node is associated with referencing node.
+    $result = entity_query('node')
+      ->condition('type', $this->referencing_type)
+      ->execute();
+
+    $referencing_nid = key($result);
+    $referencing_node = node_load($referencing_nid);
+    $this->assertEqual($referenced_nid, $referencing_node->test_field[LANGUAGE_NOT_SPECIFIED][0]['target_id'], 'Newly created node is referenced from the referencing node.');
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php
new file mode 100644
index 0000000..fb4b4df
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceAutocompleteTest.php
@@ -0,0 +1,114 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceAutocompleteTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\taxonomy\Tests\TaxonomyTestBase;
+
+class EntityReferenceAutocompleteTest extends TaxonomyTestBase {
+
+  public static $modules = array('entity_reference', 'taxonomy');
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Autocomplete',
+      'description' => 'Tests autocomplete menu item.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  function setUp() {
+    parent::setUp();
+
+    $this->admin_user = $this->drupalCreateUser(array('administer taxonomy', 'bypass node access'));
+    $this->drupalLogin($this->admin_user);
+    $this->vocabulary = $this->createVocabulary();
+
+    $this->field_name = 'taxonomy_' . $this->vocabulary->id();
+
+    $field = array(
+      'field_name' => $this->field_name,
+      'type' => 'entity_reference',
+      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+      'settings' => array(
+        'target_type' => 'taxonomy_term',
+      ),
+    );
+    field_create_field($field);
+
+    $this->instance = array(
+      'field_name' => $this->field_name,
+      'bundle' => 'article',
+      'entity_type' => 'node',
+      'widget' => array(
+        'type' => 'options_select',
+      ),
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          'target_bundles' => array(
+            $this->vocabulary->id(),
+          ),
+          'auto_create' => TRUE,
+        ),
+      ),
+    );
+    field_create_instance($this->instance);
+    entity_get_display('node', 'article', 'default')
+      ->setComponent($this->instance['field_name'], array(
+        'type' => 'entity_reference_label',
+      ))
+      ->save();
+  }
+
+  /**
+   * Tests autocompletion edge cases with slashes in the names.
+   */
+  function testTermAutocompletion() {
+    // Add a term with a slash in the name.
+    $first_term = $this->createTerm($this->vocabulary);
+    $first_term->name = '10/16/2011';
+    taxonomy_term_save($first_term);
+    // Add another term that differs after the slash character.
+    $second_term = $this->createTerm($this->vocabulary);
+    $second_term->name = '10/17/2011';
+    taxonomy_term_save($second_term);
+    // Add another term that has both a comma and a slash character.
+    $third_term = $this->createTerm($this->vocabulary);
+    $third_term->name = 'term with, a comma and / a slash';
+    taxonomy_term_save($third_term);
+
+    // Set the path prefix to point to entity reference's autocomplete path.
+    $path_prefix = 'entity_reference/autocomplete/single/' . $this->field_name . '/node/article/NULL';
+
+    // Try to autocomplete a term name that matches both terms.
+    // We should get both term in a json encoded string.
+    $input = '10/';
+    $result = $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+    $data = drupal_json_decode($result);
+    $this->assertEqual(strip_tags($data[$first_term->name. ' (1)']), check_plain($first_term->name), 'Autocomplete returned the first matching term');
+    $this->assertEqual(strip_tags($data[$second_term->name. ' (2)']), check_plain($second_term->name), 'Autocomplete returned the second matching term');
+
+    // Try to autocomplete a term name that matches first term.
+    // We should only get the first term in a json encoded string.
+    $input = '10/16';
+    $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+    $target = array($first_term->name . ' (1)' => '<div class="reference-autocomplete">' . check_plain($first_term->name) . '</div>');
+    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns only the expected matching term.');
+
+    // Try to autocomplete a term name with both a comma and a slash.
+    $input = '"term with, comma and / a';
+    $this->drupalGet($path_prefix, array('query' => array('q' => $input)));
+    $n = $third_term->name;
+    // Term names containing commas or quotes must be wrapped in quotes.
+    if (strpos($third_term->name, ',') !== FALSE || strpos($third_term->name, '"') !== FALSE) {
+      $n = '"' . str_replace('"', '""', $third_term->name) .  ' (3)"';
+    }
+    $target = array($n => '<div class="reference-autocomplete">' . check_plain($third_term->name) . '</div>');
+    $this->assertRaw(drupal_json_encode($target), 'Autocomplete returns a term containing a comma and a slash.');
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php
new file mode 100644
index 0000000..ab6a6c3
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceItemTest.php
@@ -0,0 +1,103 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceItemTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+use Drupal\entity_reference\Type\EntityReferenceItem;
+use Drupal\Core\Entity\Field\FieldItemInterface;
+use Drupal\Core\Entity\Field\FieldInterface;
+
+/**
+ * Tests the new entity API for the entity reference field type.
+ */
+class EntityReferenceItemTest extends WebTestBase {
+
+  /**
+   * Modules to enable.
+   *
+   * @var array
+   */
+  public static $modules = array('field', 'field_sql_storage', 'entity_test', 'options', 'entity_reference');
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity reference field API',
+      'description' => 'Tests using entity fields of the entity-reference field type.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public function setUp() {
+    parent::setUp();
+
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'field_name' => 'field_test',
+      'type' => 'entity_reference',
+      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
+    );
+
+    field_create_field($field);
+
+    $instance = array(
+      'entity_type' => 'entity_test',
+      'field_name' => 'field_test',
+      'bundle' => 'entity_test',
+      'widget' => array(
+        'type' => 'options_select',
+      ),
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(),
+      ),
+    );
+    field_create_instance($instance);
+  }
+
+  /**
+   * Tests using entity fields of the taxonomy term reference field type.
+   */
+  public function testEntityReferenceItem() {
+    // Create a node.
+    $node1 = $this->drupalCreateNode();
+    $nid = $node1->id();
+
+    // Just being able to create the entity like this verifies a lot of
+    // code.
+    $entity = entity_create('entity_test', array('name' => 'foo'));
+    $entity->field_test->target_id = $nid;
+    $entity->save();
+
+    $this->assertTrue($entity->field_test instanceof FieldInterface, 'Field implements interface.');
+    $this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
+    $this->assertEqual($entity->field_test->target_id, $nid);
+    $this->assertEqual($entity->field_test->entity->title, $node1->label());
+    $this->assertEqual($entity->field_test->entity->id(), $nid);
+    $this->assertEqual($entity->field_test->entity->uuid(), $node1->uuid());
+
+    // Change the name of the term via the reference.
+    $new_name = $this->randomName();
+    $entity->field_test->entity->title = $new_name;
+    $entity->field_test->entity->save();
+
+    // Verify it is the correct name.
+    $node = node_load($nid);
+    $this->assertEqual($node->label(), $new_name);
+
+    // Make sure the computed node reflects updates to the node id.
+    $node2 = $this->drupalCreateNode();
+
+    $entity->field_test->target_id = $node2->nid;
+    $this->assertEqual($entity->field_test->entity->id(), $node2->id());
+    $this->assertEqual($entity->field_test->entity->title, $node2->label());
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
new file mode 100644
index 0000000..7286b5c
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionAccessTest.php
@@ -0,0 +1,495 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceSelectionAccessTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference Selection plugin.
+ */
+class EntityReferenceSelectionAccessTest extends WebTestBase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference Handlers',
+      'description' => 'Tests for the base handlers provided by Entity Reference.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('node', 'comment', 'entity_reference');
+
+  function setUp() {
+    parent::setUp();
+
+    // Create an Article node type.
+    $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
+  }
+
+  protected function assertReferencable($field, $instance, $tests, $handler_name) {
+    $handler = entity_reference_get_selection_handler($field, $instance);
+
+    foreach ($tests as $test) {
+      foreach ($test['arguments'] as $arguments) {
+        $result = call_user_func_array(array($handler, 'getReferencableEntities'), $arguments);
+        $this->assertEqual($result, $test['result'], format_string('Valid result set returned by @handler.', array('@handler' => $handler_name)));
+
+        $result = call_user_func_array(array($handler, 'countReferencableEntities'), $arguments);
+        if (!empty($test['result'])) {
+          $bundle = key($test['result']);
+          $count = count($test['result'][$bundle]);
+        }
+        else {
+          $count = 0;
+        }
+
+        $this->assertEqual($result, $count, format_string('Valid count returned by @handler.', array('@handler' => $handler_name)));
+      }
+    }
+  }
+
+  /**
+   * Test the node-specific overrides of the entity handler.
+   */
+  public function testNodeHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => '1',
+    );
+    $instance = array(
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+    );
+
+    // Build a set of test data.
+    // Titles contain HTML-special characters to test escaping.
+    $node_values = array(
+      'published1' => array(
+        'type' => 'article',
+        'status' => NODE_PUBLISHED,
+        'title' => 'Node published1 (<&>)',
+        'uid' => 1,
+      ),
+      'published2' => array(
+        'type' => 'article',
+        'status' => NODE_PUBLISHED,
+        'title' => 'Node published2 (<&>)',
+        'uid' => 1,
+      ),
+      'unpublished' => array(
+        'type' => 'article',
+        'status' => NODE_NOT_PUBLISHED,
+        'title' => 'Node unpublished (<&>)',
+        'uid' => 1,
+      ),
+    );
+
+    $nodes = array();
+    $node_labels = array();
+    foreach ($node_values as $key => $values) {
+      $node = entity_create('node', $values);
+      $node->save();
+      $nodes[$key] = $node;
+      $node_labels[$key] = check_plain($node->label());
+    }
+
+    // Test as a non-admin.
+    $normal_user = $this->drupalCreateUser(array('access content'));
+    $GLOBALS['user'] = $normal_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'article' => array(
+            $nodes['published1']->nid => $node_labels['published1'],
+            $nodes['published2']->nid => $node_labels['published2'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('published1', 'CONTAINS'),
+          array('Published1', 'CONTAINS'),
+        ),
+        'result' => array(
+          'article' => array(
+            $nodes['published1']->nid => $node_labels['published1'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('published2', 'CONTAINS'),
+          array('Published2', 'CONTAINS'),
+        ),
+        'result' => array(
+          'article' => array(
+            $nodes['published2']->nid => $node_labels['published2'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid node', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('Node unpublished', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'Node handler');
+
+    // Test as an admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'article' => array(
+            $nodes['published1']->nid => $node_labels['published1'],
+            $nodes['published2']->nid => $node_labels['published2'],
+            $nodes['unpublished']->nid => $node_labels['unpublished'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Node unpublished', 'CONTAINS'),
+        ),
+        'result' => array(
+          'article' => array(
+            $nodes['unpublished']->nid => $node_labels['unpublished'],
+          ),
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'Node handler (admin)');
+  }
+
+  /**
+   * Test the user-specific overrides of the entity handler.
+   */
+  public function testUserHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'user',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => '1',
+    );
+    $instance = array(
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+    );
+
+    // Build a set of test data.
+    $user_values = array(
+      'anonymous' => user_load(0),
+      'admin' => user_load(1),
+      'non_admin' => array(
+        'name' => 'non_admin <&>',
+        'mail' => 'non_admin@example.com',
+        'roles' => array(),
+        'pass' => user_password(),
+        'status' => 1,
+      ),
+      'blocked' => array(
+        'name' => 'blocked <&>',
+        'mail' => 'blocked@example.com',
+        'roles' => array(),
+        'pass' => user_password(),
+        'status' => 0,
+      ),
+    );
+
+    $user_values['anonymous']->name = config('user.settings')->get('anonymous');
+    $users = array();
+
+    $user_labels = array();
+    foreach ($user_values as $key => $values) {
+      if (is_array($values)) {
+        $account = entity_create('user', $values);
+        $account->save();
+      }
+      else {
+        $account = $values;
+      }
+      $users[$key] = $account;
+      $user_labels[$key] = check_plain($account->name);
+    }
+
+    // Test as a non-admin.
+    $GLOBALS['user'] = $users['non_admin'];
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'user' => array(
+            $users['admin']->uid => $user_labels['admin'],
+            $users['non_admin']->uid => $user_labels['non_admin'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('non_admin', 'CONTAINS'),
+          array('NON_ADMIN', 'CONTAINS'),
+        ),
+        'result' => array(
+          'user' => array(
+            $users['non_admin']->uid => $user_labels['non_admin'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid user', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('blocked', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'User handler');
+
+    $GLOBALS['user'] = $users['admin'];
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'user' => array(
+            $users['anonymous']->uid => $user_labels['anonymous'],
+            $users['admin']->uid => $user_labels['admin'],
+            $users['non_admin']->uid => $user_labels['non_admin'],
+            $users['blocked']->uid => $user_labels['blocked'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('blocked', 'CONTAINS'),
+        ),
+        'result' => array(
+          'user' => array(
+            $users['blocked']->uid => $user_labels['blocked'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Anonymous', 'CONTAINS'),
+          array('anonymous', 'CONTAINS'),
+        ),
+        'result' => array(
+          'user' => array(
+            $users['anonymous']->uid => $user_labels['anonymous'],
+          ),
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'User handler (admin)');
+  }
+
+  /**
+   * Test the comment-specific overrides of the entity handler.
+   */
+  public function testCommentHandler() {
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'comment',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => '1',
+    );
+    $instance = array(
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+        ),
+      ),
+    );
+
+    // Build a set of test data.
+    $node_values = array(
+      'published' => array(
+        'type' => 'article',
+        'status' => 1,
+        'title' => 'Node published',
+        'uid' => 1,
+      ),
+      'unpublished' => array(
+        'type' => 'article',
+        'status' => 0,
+        'title' => 'Node unpublished',
+        'uid' => 1,
+      ),
+    );
+    $nodes = array();
+    foreach ($node_values as $key => $values) {
+      $node = entity_create('node', $values);
+      $node->save();
+      $nodes[$key] = $node;
+    }
+
+    $comment_values = array(
+      'published_published' => array(
+        'nid' => $nodes['published']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_PUBLISHED,
+        'subject' => 'Comment Published <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+      'published_unpublished' => array(
+        'nid' => $nodes['published']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_NOT_PUBLISHED,
+        'subject' => 'Comment Unpublished <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+      'unpublished_published' => array(
+        'nid' => $nodes['unpublished']->nid,
+        'uid' => 1,
+        'cid' => NULL,
+        'pid' => 0,
+        'status' => COMMENT_NOT_PUBLISHED,
+        'subject' => 'Comment Published on Unpublished node <&>',
+        'language' => LANGUAGE_NOT_SPECIFIED,
+      ),
+    );
+
+    $comments = array();
+    $comment_labels = array();
+    foreach ($comment_values as $key => $values) {
+      $comment = entity_create('comment', $values);
+      $comment->save();
+      $comments[$key] = $comment;
+      $comment_labels[$key] = check_plain($comment->label());
+    }
+
+    // Test as a non-admin.
+    $normal_user = $this->drupalCreateUser(array('access content', 'access comments'));
+    $GLOBALS['user'] = $normal_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'comment_node_article' => array(
+            $comments['published_published']->cid => $comment_labels['published_published'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('Published', 'CONTAINS'),
+        ),
+        'result' => array(
+          'comment_node_article' => array(
+            $comments['published_published']->cid => $comment_labels['published_published'],
+          ),
+        ),
+      ),
+      array(
+        'arguments' => array(
+          array('invalid comment', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+      array(
+        'arguments' => array(
+          array('Comment Unpublished', 'CONTAINS'),
+        ),
+        'result' => array(),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler');
+
+    // Test as a comment admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'comment_node_article' => array(
+            $comments['published_published']->cid => $comment_labels['published_published'],
+            $comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
+          ),
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler (comment admin)');
+
+    // Test as a node and comment admin.
+    $admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments', 'bypass node access'));
+    $GLOBALS['user'] = $admin_user;
+    $referencable_tests = array(
+      array(
+        'arguments' => array(
+          array(NULL, 'CONTAINS'),
+        ),
+        'result' => array(
+          'comment_node_article' => array(
+            $comments['published_published']->cid => $comment_labels['published_published'],
+            $comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
+            $comments['unpublished_published']->cid => $comment_labels['unpublished_published'],
+          ),
+        ),
+      ),
+    );
+    $this->assertReferencable($field, $instance, $referencable_tests, 'Comment handler (comment + node admin)');
+  }
+}
diff --git a/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
new file mode 100644
index 0000000..418d85c
--- /dev/null
+++ b/core/modules/entity_reference/lib/Drupal/entity_reference/Tests/EntityReferenceSelectionSortTest.php
@@ -0,0 +1,150 @@
+<?php
+
+/**
+ * @file
+ * Contains \Drupal\entity_reference\Tests\EntityReferenceSelectionSortTest.
+ */
+
+namespace Drupal\entity_reference\Tests;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests the Entity reference Selection plugin.
+ */
+class EntityReferenceSelectionSortTest extends WebTestBase {
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity Reference handlers sort',
+      'description' => 'Test sorting referenced items.',
+      'group' => 'Entity Reference',
+    );
+  }
+
+  public static $modules = array('node', 'entity_reference');
+
+  function setUp() {
+    parent::setUp();
+
+    // Create an Article node type.
+    $this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
+  }
+
+  /**
+   * Assert sorting by field and property.
+   */
+  public function testSort() {
+    // Add text field to entity, to sort by.
+    $field_info = array(
+      'field_name' => 'field_text',
+      'type' => 'text',
+      'entity_types' => array('node'),
+    );
+    field_create_field($field_info);
+
+    $instance_info = array(
+      'label' => 'Text Field',
+      'field_name' => 'field_text',
+      'entity_type' => 'node',
+      'bundle' => 'article',
+      'settings' => array(),
+      'required' => FALSE,
+    );
+    field_create_instance($instance_info);
+
+
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => 1,
+    );
+
+    $instance = array(
+      'settings' => array(
+        'handler' => 'base',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+          // Add sorting.
+          'sort' => array(
+            'field' => 'field_text.value',
+            'direction' => 'DESC',
+          ),
+        ),
+      ),
+    );
+
+    // Build a set of test data.
+    $node_values = array(
+      'published1' => array(
+        'type' => 'article',
+        'status' => 1,
+        'title' => 'Node published1 (<&>)',
+        'uid' => 1,
+        'field_text' => array(
+          LANGUAGE_NOT_SPECIFIED => array(
+            array(
+              'value' => 1,
+            ),
+          ),
+        ),
+      ),
+      'published2' => array(
+        'type' => 'article',
+        'status' => 1,
+        'title' => 'Node published2 (<&>)',
+        'uid' => 1,
+        'field_text' => array(
+          LANGUAGE_NOT_SPECIFIED => array(
+            array(
+              'value' => 2,
+            ),
+          ),
+        ),
+      ),
+    );
+
+    $nodes = array();
+    $node_labels = array();
+    foreach ($node_values as $key => $values) {
+      $node = entity_create('node', $values);
+      $node->save();
+      $nodes[$key] = $node;
+      $node_labels[$key] = check_plain($node->label());
+    }
+
+    // Test as a non-admin.
+    $normal_user = $this->drupalCreateUser(array('access content'));
+    $GLOBALS['user'] = $normal_user;
+
+    $handler = entity_reference_get_selection_handler($field, $instance);
+
+    // Not only assert the result, but make sure the keys are sorted as
+    // expected.
+    $result = $handler->getReferencableEntities();
+    $expected_result = array(
+      $nodes['published2']->nid => $node_labels['published2'],
+      $nodes['published1']->nid => $node_labels['published1'],
+    );
+    $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
+
+    // Assert sort by property.
+    $instance['settings']['handler_settings']['sort'] = array(
+      'field' => 'nid',
+      'direction' => 'ASC',
+    );
+    $handler = entity_reference_get_selection_handler($field, $instance);
+    $result = $handler->getReferencableEntities();
+    $expected_result = array(
+      $nodes['published1']->nid => $node_labels['published1'],
+      $nodes['published2']->nid => $node_labels['published2'],
+    );
+    $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
+  }
+}
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml b/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml
new file mode 100644
index 0000000..2916abe
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/config/views.view.test_entity_reference.yml
@@ -0,0 +1,79 @@
+api_version: '3.0'
+base_field: nid
+base_table: node
+core: 8.x
+description: ''
+disabled: '0'
+display:
+  default:
+    display_plugin: default
+    id: default
+    display_title: Master
+    position: ''
+    display_options:
+      access:
+        type: perm
+      cache:
+        type: none
+      query:
+        type: views_query
+      exposed_form:
+        type: basic
+      pager:
+        type: full
+      style:
+        type: default
+      row:
+        type: fields
+      fields:
+        title:
+          id: title
+          table: node
+          field: title
+          label: ''
+          alter:
+            alter_text: '0'
+            make_link: '0'
+            absolute: '0'
+            trim: '0'
+            word_boundary: '0'
+            ellipsis: '0'
+            strip_tags: '0'
+            html: '0'
+          hide_empty: '0'
+          empty_zero: '0'
+          link_to_node: '1'
+      filters:
+        status:
+          value: '1'
+          table: node
+          field: status
+          id: status
+          expose:
+            operator: '0'
+          group: '1'
+      sorts:
+        created:
+          id: created
+          table: node
+          field: created
+          order: DESC
+  entity_reference_1:
+    display_plugin: entity_reference
+    id: entity_reference_1
+    display_title: EntityReference
+    position: ''
+    display_options:
+      style:
+        type: entity_reference
+        options:
+          grouping: {  }
+          search_fields:
+            title: title
+      pager:
+        type: none
+        options:
+          offset: '0'
+human_name: 'Entity reference'
+name: test_entity_reference
+tag: ''
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info
new file mode 100644
index 0000000..32b6452
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.info
@@ -0,0 +1,7 @@
+name = "Entity reference Test"
+description = "Support module for the Entity reference tests."
+core = 8.x
+dependencies[] = entity_reference
+package = Testing
+version = VERSION
+hidden = TRUE
diff --git a/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module
new file mode 100644
index 0000000..6bbe7e9
--- /dev/null
+++ b/core/modules/entity_reference/tests/modules/entity_reference_test/entity_reference_test.module
@@ -0,0 +1,6 @@
+<?php
+
+/**
+ * @file
+ * Helper module for the Entity reference tests.
+ */
diff --git a/core/modules/field/field.api.php b/core/modules/field/field.api.php
index 27304f4..3386eac 100644
--- a/core/modules/field/field.api.php
+++ b/core/modules/field/field.api.php
@@ -1076,7 +1076,7 @@ function hook_field_attach_view_alter(&$output, $context) {
   // Append RDF term mappings on displayed taxonomy links.
   foreach (element_children($output) as $field_name) {
     $element = &$output[$field_name];
-    if ($element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'taxonomy_term_reference_link') {
+    if ($element['#field_type'] == 'entity_reference' && $element['#formatter'] == 'entity_reference_label') {
       foreach ($element['#items'] as $delta => $item) {
         $term = $item['taxonomy_term'];
         if (!empty($term->rdf_mapping['rdftype'])) {
diff --git a/core/modules/field/field.crud.inc b/core/modules/field/field.crud.inc
index f6ee8a2..a5e582b 100644
--- a/core/modules/field/field.crud.inc
+++ b/core/modules/field/field.crud.inc
@@ -865,14 +865,11 @@ function field_purge_batch($batch_size) {
     // field_purge_data() will need the field array.
     $field = field_info_field_by_id($instance['field_id']);
     // Retrieve some entities.
-    $query = $factory->get($entity_type)
+    $results = $factory->get($entity_type)
       ->condition('id:' . $field['id'] . '.deleted', 1)
-      ->range(0, $batch_size);
-    // If there's no bundle key, all results will have the same bundle.
-    if (!empty($info[$entity_type]['entity_keys']['bundle'])) {
-      $query->condition($info[$entity_type]['entity_keys']['bundle'], $ids->bundle);
-    }
-    $results = $query->execute();
+      ->condition($info[$entity_type]['entity_keys']['bundle'], $ids->bundle)
+      ->range(0, $batch_size)
+      ->execute();
 
     if ($results) {
       $entities = array();
diff --git a/core/modules/field/field.views.inc b/core/modules/field/field.views.inc
index 2c5d5db..de22349 100644
--- a/core/modules/field/field.views.inc
+++ b/core/modules/field/field.views.inc
@@ -127,9 +127,6 @@ function field_views_field_default_views_data($field) {
       $group_name = $groups[$entity];
     }
 
-    if (!isset($entity_info['base_table'])) {
-      continue;
-    }
     $entity_tables[$entity_info['base_table']] = $entity;
     $current_tables[$entity] = $entity_info['base_table'];
     if (isset($entity_info['revision_table'])) {
@@ -204,9 +201,6 @@ function field_views_field_default_views_data($field) {
     $aliases = array();
     $also_known = array();
     foreach ($all_labels as $entity_name => $labels) {
-      if (!isset($current_tables[$entity_name])) {
-        continue;
-      }
       foreach ($labels as $label_name => $true) {
         if ($type == FIELD_LOAD_CURRENT) {
           if ($group_name != $groups[$entity_name] || $label != $label_name) {
diff --git a/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php b/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
index bf02e2b..c7c9984 100644
--- a/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
+++ b/core/modules/field_sql_storage/lib/Drupal/field_sql_storage/Entity/Tables.php
@@ -95,7 +95,7 @@ function addField($field, $type, $langcode) {
       // field), a field API field (a configurable field).
       $specifier = $specifiers[$key];
       // First, check for field API fields by trying to retrieve the field specified.
-      // Normally it is a field name, but field_purge_batch() is passing in 
+      // Normally it is a field name, but field_purge_batch() is passing in
       // id:$field_id so check that first.
       if (substr($specifier, 0, 3) == 'id:') {
         $field = field_info_field_by_id(substr($specifier, 3));
@@ -125,9 +125,11 @@ function addField($field, $type, $langcode) {
           // also use the property definitions for column.
           if ($key < $count) {
             $relationship_specifier = $specifiers[$key + 1];
-            $propertyDefinitions = typed_data()
-              ->create(array('type' => $field['type'] . '_field'))
-              ->getPropertyDefinitions();
+
+            // Get the field definitions form a mocked entity.
+            $entity = entity_create($entity_type, array());
+            $propertyDefinitions = $entity->{$field['field_name']}->getPropertyDefinitions();
+
             // If the column is not yet known, ie. the
             // $node->field_image->entity case then use the id source as the
             // column.
diff --git a/core/modules/field_ui/field_ui.module b/core/modules/field_ui/field_ui.module
index dd2a1cc..a04c0dd 100644
--- a/core/modules/field_ui/field_ui.module
+++ b/core/modules/field_ui/field_ui.module
@@ -76,8 +76,8 @@ function field_ui_menu() {
           // Extract path information from the bundle.
           $path = $bundle_info['admin']['path'];
           // Different bundles can appear on the same path (e.g. %node_type and
-          // %comment_node_type). To allow field_ui_instance_load() to extract
-          // the actual bundle object from the translated menu router path
+          // %comment_node_type). To allow field_ui_menu_load() to extract the
+          // actual bundle object from the translated menu router path
           // arguments, we need to identify the argument position of the bundle
           // name string ('bundle argument') and pass that position to the menu
           // loader. The position needs to be casted into a string; otherwise it
@@ -90,7 +90,7 @@ function field_ui_menu() {
             $bundle_arg = $bundle_name;
             $bundle_pos = '0';
           }
-          // This is the position of the %field_ui_instance placeholder in the
+          // This is the position of the %field_ui_menu placeholder in the
           // items below.
           $field_position = count(explode('/', $path)) + 1;
 
@@ -109,15 +109,15 @@ function field_ui_menu() {
             'weight' => 1,
             'file' => 'field_ui.admin.inc',
           ) + $access;
-          $items["$path/fields/%field_ui_instance"] = array(
+          $items["$path/fields/%field_ui_menu"] = array(
             'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
-            'title callback' => 'field_ui_instance_title',
+            'title callback' => 'field_ui_menu_title',
             'title arguments' => array($field_position),
             'page callback' => 'drupal_get_form',
             'page arguments' => array('field_ui_field_edit_form', $field_position),
             'file' => 'field_ui.admin.inc',
           ) + $access;
-          $items["$path/fields/%field_ui_instance/edit"] = array(
+          $items["$path/fields/%field_ui_menu/edit"] = array(
             'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
             'title' => 'Edit',
             'page callback' => 'drupal_get_form',
@@ -125,7 +125,7 @@ function field_ui_menu() {
             'type' => MENU_DEFAULT_LOCAL_TASK,
             'file' => 'field_ui.admin.inc',
           ) + $access;
-          $items["$path/fields/%field_ui_instance/field-settings"] = array(
+          $items["$path/fields/%field_ui_menu/field-settings"] = array(
             'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
             'title' => 'Field settings',
             'page callback' => 'drupal_get_form',
@@ -133,7 +133,7 @@ function field_ui_menu() {
             'type' => MENU_LOCAL_TASK,
             'file' => 'field_ui.admin.inc',
           ) + $access;
-          $items["$path/fields/%field_ui_instance/widget-type"] = array(
+          $items["$path/fields/%field_ui_menu/widget-type"] = array(
             'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
             'title' => 'Widget type',
             'page callback' => 'drupal_get_form',
@@ -141,7 +141,7 @@ function field_ui_menu() {
             'type' => MENU_LOCAL_TASK,
             'file' => 'field_ui.admin.inc',
           ) + $access;
-          $items["$path/fields/%field_ui_instance/delete"] = array(
+          $items["$path/fields/%field_ui_menu/delete"] = array(
             'load arguments' => array($entity_type, $bundle_arg, $bundle_pos, '%map'),
             'title' => 'Delete',
             'page callback' => 'drupal_get_form',
@@ -211,12 +211,12 @@ function field_ui_menu() {
  *
  * @ingroup field
  */
-function field_ui_instance_load($field_name, $entity_type, $bundle_name, $bundle_pos, $map) {
+function field_ui_menu_load($field_name, $entity_type, $bundle_name, $bundle_pos, $map) {
   // Extract the actual bundle name from the translated argument map.
   // The menu router path to manage fields of an entity can be shared among
   // multiple bundles. For example:
-  // - admin/structure/types/manage/%node_type/fields/%field_ui_instance
-  // - admin/structure/types/manage/%comment_node_type/fields/%field_ui_instance
+  // - admin/structure/types/manage/%node_type/fields/%field_ui_menu
+  // - admin/structure/types/manage/%comment_node_type/fields/%field_ui_menu
   // The menu system will automatically load the correct bundle depending on the
   // actual path arguments, but this menu loader function only receives the node
   // type string as $bundle_name, which is not the bundle name for comments.
@@ -242,7 +242,7 @@ function field_ui_instance_load($field_name, $entity_type, $bundle_name, $bundle
  *
  * @see field_ui_menu()
  */
-function field_ui_instance_title($instance) {
+function field_ui_menu_title($instance) {
   return $instance['label'];
 }
 
diff --git a/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php b/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php
index 14677eb..7298c36 100644
--- a/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php
+++ b/core/modules/field_ui/lib/Drupal/field_ui/Tests/ManageFieldsTest.php
@@ -450,27 +450,4 @@ function testWidgetChange() {
     $this->assertFieldByXPath("//select[@name='widget_type']", 'options_buttons');
   }
 
-  /**
-   * Tests that deletion removes fields and instances as expected for a term.
-   */
-  function testDeleteTaxonomyField() {
-    // Create a new field.
-    $bundle_path = 'admin/structure/taxonomy/tags';
-    $edit1 = array(
-      'fields[_add_new_field][label]' => $this->field_label,
-      'fields[_add_new_field][field_name]' => $this->field_name_input,
-    );
-    $this->fieldUIAddNewField($bundle_path, $edit1);
-
-    // Delete the field.
-    $this->fieldUIDeleteField($bundle_path, $this->field_name, $this->field_label, 'Tags');
-
-    // Reset the fields info.
-    field_info_cache_clear();
-    // Check that the field instance was deleted.
-    $this->assertNull(field_info_instance('taxonomy_term', $this->field_name, 'tags'), 'Field instance was deleted.');
-    // Check that the field was deleted too.
-    $this->assertNull(field_info_field($this->field_name), 'Field was deleted.');
-  }
-
 }
diff --git a/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php b/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php
new file mode 100644
index 0000000..1f46441
--- /dev/null
+++ b/core/modules/file/lib/Drupal/file/Plugin/entity_reference/selection/FileSelection.php
@@ -0,0 +1,36 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\file\Plugin\Type\selection\FileSelection.
+ */
+
+namespace Drupal\file\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;
+
+/**
+ * Provides specific access control for the file entity type.
+ *
+ * @Plugin(
+ *   id = "base_file",
+ *   module = "entity_reference",
+ *   label = @Translation("File selection"),
+ *   entity_types = {"file"},
+ *   group = "base",
+ *   weight = 1
+ * )
+ */
+class FileSelection extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::buildEntityQuery().
+   */
+  public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = parent::buildEntityQuery($match, $match_operator);
+    $query->condition('status', FILE_STATUS_PERMANENT);
+  }
+}
diff --git a/core/modules/filter/filter.admin-rtl.css b/core/modules/filter/filter.admin-rtl.css
index 0370a98..10620bf 100644
--- a/core/modules/filter/filter.admin-rtl.css
+++ b/core/modules/filter/filter.admin-rtl.css
@@ -1,7 +1,7 @@
 
 /**
  * @file
- * Right-to-Left administrative styling for the Filter module.
+ * RTL admin styling for the Filter module.
  */
 
 /**
diff --git a/core/modules/filter/filter.admin.inc b/core/modules/filter/filter.admin.inc
index 3c01ac2..a62f8e3 100644
--- a/core/modules/filter/filter.admin.inc
+++ b/core/modules/filter/filter.admin.inc
@@ -2,11 +2,11 @@
 
 /**
  * @file
- * Administrative page callbacks for the Filter module.
+ * Admin page callbacks for the Filter module.
  */
 
 /**
- * Page callback: Form constructor for a form to list and reorder text formats.
+ * Form constructor for a form to list and reorder text formats.
  *
  * @see filter_menu()
  * @see filter_admin_overview_submit()
@@ -103,7 +103,6 @@ function filter_admin_overview_submit($form, &$form_state) {
  *     enabled (1) or not (0). Defaults to 1.
  *   - weight: (optional) The weight of the text format, which controls its
  *     placement in text format lists. If omitted, the weight is set to 0.
- *     Defaults to NULL.
  *
  * @return
  *   A form array.
@@ -130,8 +129,8 @@ function filter_admin_format_page($format = NULL) {
  *     save. If this corresponds to an existing text format, that format will be
  *     updated; otherwise, a new format will be created.
  *   - name: The title of the text format.
- *   - cache: (optional) An integer indicating whether the text format is
- *     cacheable (1) or not (0). Defaults to 1.
+ *   - cache: An integer indicating whether the text format is cacheable (1) or
+ *     not (0). Defaults to 1.
  *   - status: (optional) An integer indicating whether the text format is
  *     enabled (1) or not (0). Defaults to 1.
  *   - weight: (optional) The weight of the text format, which controls its
@@ -247,9 +246,12 @@ function filter_admin_format_form($form, &$form_state, $format) {
   }
 
   // Filter settings.
+  $form['filter_settings_title'] = array(
+    '#type' => 'item',
+    '#title' => t('Filter settings'),
+  );
   $form['filter_settings'] = array(
     '#type' => 'vertical_tabs',
-    '#title' => t('Filter settings'),
   );
 
   foreach ($filter_info as $name => $filter) {
@@ -281,7 +283,7 @@ function filter_admin_format_form($form, &$form_state, $format) {
 /**
  * Returns HTML for a text format's filter order form.
  *
- * @param array $variables
+ * @param $variables
  *   An associative array containing:
  *   - element: A render element representing the form.
  *
@@ -363,7 +365,7 @@ function filter_admin_format_form_submit($form, &$form_state) {
 }
 
 /**
- * Page callback: Form constructor to confirm the text format deletion.
+ * Form constructor for the text format deletion confirmation form.
  *
  * @param $format
  *   An object representing a text format.
diff --git a/core/modules/filter/filter.module b/core/modules/filter/filter.module
index 182bbb1..c4b596a 100644
--- a/core/modules/filter/filter.module
+++ b/core/modules/filter/filter.module
@@ -359,12 +359,6 @@ function filter_format_exists($format_id) {
 /**
  * Displays a text format form title.
  *
- * @param object $format_id
- *   A format object.
- *
- * @return string
- *   The name of the format.
- *
  * @see filter_menu()
  */
 function filter_admin_format_title($format) {
@@ -440,8 +434,7 @@ function filter_modules_disabled($modules) {
  *
  * @param $account
  *   (optional) If provided, only those formats that are allowed for this user
- *   account will be returned. All formats will be returned otherwise. Defaults
- *   to NULL.
+ *   account will be returned. All formats will be returned otherwise.
  *
  * @return
  *   An array of text format objects, keyed by the format ID and ordered by
@@ -554,7 +547,7 @@ function filter_get_formats_by_role($rid) {
  *
  * @param $account
  *   (optional) The user account to check. Defaults to the currently logged-in
- *   user. Defaults to NULL.
+ *   user.
  *
  * @return
  *   The ID of the user's default text format.
@@ -619,15 +612,15 @@ function filter_get_filter_types_by_format($format_id) {
  * format is initialized to output plain text. Installation profiles and site
  * administrators have the freedom to configure it further.
  *
- * Note that the fallback format is completely distinct from the default format,
- * which differs per user and is simply the first format which that user has
- * access to. The default and fallback formats are only guaranteed to be the
- * same for users who do not have access to any other format; otherwise, the
- * fallback format's weight determines its placement with respect to the user's
- * other formats.
+ * Note that the fallback format is completely distinct from the default
+ * format, which differs per user and is simply the first format which that
+ * user has access to. The default and fallback formats are only guaranteed to
+ * be the same for users who do not have access to any other format; otherwise,
+ * the fallback format's weight determines its placement with respect to the
+ * user's other formats.
  *
- * Any modules implementing a format deletion functionality must not delete this
- * format.
+ * Any modules implementing a format deletion functionality must not delete
+ * this format.
  *
  * @return
  *   The ID of the fallback text format.
@@ -647,9 +640,6 @@ function filter_fallback_format() {
 
 /**
  * Returns the title of the fallback text format.
- *
- * @return string
- *   The title of the fallback text format.
  */
 function filter_fallback_format_title() {
   $fallback_format = filter_format_load(filter_fallback_format());
@@ -658,9 +648,6 @@ function filter_fallback_format_title() {
 
 /**
  * Returns a list of all filters provided by modules.
- *
- * @return array
- *   An array of filter formats.
  */
 function filter_get_filters() {
   $filters = &drupal_static(__FUNCTION__, array());
@@ -812,17 +799,16 @@ function filter_list_format($format_id) {
  * @param $text
  *   The text to be filtered.
  * @param $format_id
- *   (optional) The format ID of the text to be filtered. If no format is
- *   assigned, the fallback format will be used. Defaults to NULL.
+ *   The format ID of the text to be filtered. If no format is assigned, the
+ *   fallback format will be used.
  * @param $langcode
- *   (optional) The language code of the text to be filtered, e.g. 'en' for
+ *   Optional: the language code of the text to be filtered, e.g. 'en' for
  *   English. This allows filters to be language aware so language specific
- *   text replacement can be implemented. Defaults to an empty string.
+ *   text replacement can be implemented.
  * @param $cache
- *   (optional) A Boolean indicating whether to cache the filtered output in the
- *   {cache_filter} table. The caller may set this to FALSE when the output is
- *   already cached elsewhere to avoid duplicate cache lookups and storage.
- *   Defaults to FALSE.
+ *   Boolean whether to cache the filtered output in the {cache_filter} table.
+ *   The caller may set this to FALSE when the output is already cached
+ *   elsewhere to avoid duplicate cache lookups and storage.
  * @param array $filter_types_to_skip
  *   (optional) An array of filter types to skip, or an empty array (default)
  *   to skip no filter types. All of the format's filters will be applied,
@@ -1085,7 +1071,7 @@ function filter_form_access_denied($element) {
 /**
  * Returns HTML for a text format-enabled form element.
  *
- * @param array $variables
+ * @param $variables
  *   An associative array containing:
  *   - element: A render element containing #children and #description.
  *
@@ -1110,7 +1096,7 @@ function theme_text_format_wrapper($variables) {
  *   An object representing the text format.
  * @param $account
  *   (optional) The user account to check access for; if omitted, the currently
- *   logged-in user is used. Defaults to NULL.
+ *   logged-in user is used.
  *
  * @return
  *   Boolean TRUE if the user is allowed to access the given format.
@@ -1246,11 +1232,9 @@ function filter_dom_serialize($dom_document) {
  * @param $dom_element
  *   The element potentially containing a CDATA node.
  * @param $comment_start
- *   (optional) A string to use as a comment start marker to escape the CDATA
- *   declaration. Defaults to '//'.
+ *   String to use as a comment start marker to escape the CDATA declaration.
  * @param $comment_end
- *   (optional) A string to use as a comment end marker to escape the CDATA
- *   declaration. Defaults to an empty string.
+ *   String to use as a comment end marker to escape the CDATA declaration.
  */
 function filter_dom_serialize_escape_cdata_element($dom_document, $dom_element, $comment_start = '//', $comment_end = '') {
   foreach ($dom_element->childNodes as $node) {
@@ -1285,7 +1269,7 @@ function theme_filter_tips_more_info() {
 /**
  * Returns HTML for guidelines for a text format.
  *
- * @param array $variables
+ * @param $variables
  *   An associative array containing:
  *   - format: An object representing a text format.
  *
@@ -1711,9 +1695,8 @@ function _filter_url_parse_partial_links($match) {
  *   An array containing matches to replace from preg_replace_callback(),
  *   whereas $match[1] is expected to contain the content to be filtered.
  * @param $escape
- *   (optional) A Boolean indicating whether to escape (TRUE) or unescape
- *   comments (FALSE). Defaults to NULL, indicating neither. If TRUE, statically
- *   cached $comments are reset.
+ *   (optional) Boolean whether to escape (TRUE) or unescape comments (FALSE).
+ *   Defaults to neither. If TRUE, statically cached $comments are reset.
  */
 function _filter_url_escape_comments($match, $escape = NULL) {
   static $mode, $comments = array();
diff --git a/core/modules/filter/filter.pages.inc b/core/modules/filter/filter.pages.inc
index 5b20d4f..dec59c3 100644
--- a/core/modules/filter/filter.pages.inc
+++ b/core/modules/filter/filter.pages.inc
@@ -8,14 +8,7 @@
 /**
  * Page callback: Displays a page with long filter tips.
  *
- * @param $format
- *   (optional) A filter format. Defaults to NULL.
- *
- * @return string
- *   An HTML-formatted string.
- *
  * @see filter_menu()
- * @see theme_filter_tips()
  */
 function filter_tips_long($format = NULL) {
   if (!empty($format)) {
@@ -30,7 +23,7 @@ function filter_tips_long($format = NULL) {
 /**
  * Returns HTML for a set of filter tips.
  *
- * @param array $variables
+ * @param $variables
  *   An associative array containing:
  *   - tips: An array containing descriptions and a CSS ID in the form of
  *     'module-name/filter-id' (only used when $long is TRUE) for each
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterAdminTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterAdminTest.php
index c2b76d2..9a09a76 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterAdminTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterAdminTest.php
@@ -9,16 +9,7 @@
 
 use Drupal\simpletest\WebTestBase;
 
-/**
- * Tests the administrative functionality of the Filter module.
- */
 class FilterAdminTest extends WebTestBase {
-
-  /**
-   * The installation profile to use with this test.
-   *
-   * @var string
-   */
   protected $profile = 'standard';
 
   public static function getInfo() {
@@ -45,9 +36,6 @@ function setUp() {
     $this->drupalLogin($this->admin_user);
   }
 
-  /**
-   * Tests the format administration functionality.
-   */
   function testFormatAdmin() {
     // Add text format.
     $this->drupalGet('admin/config/content/formats');
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterCrudTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterCrudTest.php
index 7b4c6f5..766736f 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterCrudTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterCrudTest.php
@@ -82,7 +82,7 @@ function testTextFormatCrud() {
   }
 
   /**
-   * Verifies that a text format is properly stored.
+   * Verify that a text format is properly stored.
    */
   function verifyTextFormat($format) {
     $t_args = array('%format' => $format->name);
@@ -120,7 +120,7 @@ function verifyTextFormat($format) {
   }
 
   /**
-   * Verifies that filters are properly stored for a text format.
+   * Verify that filters are properly stored for a text format.
    */
   function verifyFilters($format) {
     // Verify filter database records.
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterDefaultFormatTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterDefaultFormatTest.php
index 103d777..04fa520 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterDefaultFormatTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterDefaultFormatTest.php
@@ -9,9 +9,6 @@
 
 use Drupal\simpletest\WebTestBase;
 
-/**
- * Tests the default filter functionality in the Filter module.
- */
 class FilterDefaultFormatTest extends WebTestBase {
   public static function getInfo() {
     return array(
@@ -67,7 +64,7 @@ function testDefaultTextFormats() {
   }
 
   /**
-   * Rebuilds text format and permission caches in the thread running the tests.
+   * Rebuild text format and permission caches in the thread running the tests.
    */
   protected function resetFilterCaches() {
     filter_formats_reset();
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterFormatAccessTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterFormatAccessTest.php
index a71a9e9..4636610 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterFormatAccessTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterFormatAccessTest.php
@@ -9,43 +9,11 @@
 
 use Drupal\simpletest\WebTestBase;
 
-/**
- * Tests the filter format access functionality in the Filter module.
- */
 class FilterFormatAccessTest extends WebTestBase {
-  /**
-   * A user with administrative permissions.
-   *
-   * @var object
-   */
   protected $admin_user;
-
-  /**
-   * A user with 'administer filters' permission.
-   *
-   * @var object
-   */
   protected $filter_admin_user;
-
-  /**
-   * A user with permission to create and edit own content.
-   *
-   * @var object
-   */
   protected $web_user;
-
-  /**
-   * An object representing an allowed text format.
-   *
-   * @var object
-   */
   protected $allowed_format;
-
-  /**
-   * An object representing a disallowed text format.
-   *
-   * @var object
-   */
   protected $disallowed_format;
 
   public static function getInfo() {
@@ -101,9 +69,6 @@ function setUp() {
     ));
   }
 
-  /**
-   * Tests the Filter format access permissions functionality.
-   */
   function testFormatPermissions() {
     // Make sure that a regular user only has access to the text format they
     // were granted access to, as well to the fallback format.
@@ -189,11 +154,11 @@ function testFormatRoles() {
   /**
    * Tests editing a page using a disallowed text format.
    *
-   * Verifies that regular users and administrators are able to edit a page, but
-   * not allowed to change the fields which use an inaccessible text format.
-   * Also verifies that fields which use a text format that does not exist can
-   * be edited by administrators only, but that the administrator is forced to
-   * choose a new format before saving the page.
+   * Verifies that regular users and administrators are able to edit a page,
+   * but not allowed to change the fields which use an inaccessible text
+   * format. Also verifies that fields which use a text format that does not
+   * exist can be edited by administrators only, but that the administrator is
+   * forced to choose a new format before saving the page.
    */
   function testFormatWidgetPermissions() {
     $langcode = LANGUAGE_NOT_SPECIFIED;
@@ -309,7 +274,7 @@ function testFormatWidgetPermissions() {
   }
 
   /**
-   * Rebuilds text format and permission caches in the thread running the tests.
+   * Rebuild text format and permission caches in the thread running the tests.
    */
   protected function resetFilterCaches() {
     filter_formats_reset();
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterHooksTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterHooksTest.php
index 496a5f3..f01b4d2 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterHooksTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterHooksTest.php
@@ -10,7 +10,7 @@
 use Drupal\simpletest\WebTestBase;
 
 /**
- * Tests for Filter's hook invocations.
+ * Tests for filter hook invocation.
  */
 class FilterHooksTest extends WebTestBase {
 
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterSecurityTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterSecurityTest.php
index 5928a4d..813d717 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterSecurityTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterSecurityTest.php
@@ -21,13 +21,6 @@ class FilterSecurityTest extends WebTestBase {
    */
   public static $modules = array('node', 'php', 'filter_test');
 
-  /**
-   * A user with administrative permissions.
-   *
-   * @var object
-   */
-  protected $admin_user;
-
   public static function getInfo() {
     return array(
       'name' => 'Security',
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterSettingsTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterSettingsTest.php
index 6d2ab99..0a6c00c 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterSettingsTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterSettingsTest.php
@@ -13,11 +13,6 @@
  * Tests filter settings.
  */
 class FilterSettingsTest extends WebTestBase {
-  /**
-   * The installation profile to use with this test class.
-   *
-   * @var string
-   */
   protected $profile = 'testing';
 
   public static function getInfo() {
diff --git a/core/modules/filter/lib/Drupal/filter/Tests/FilterUnitTest.php b/core/modules/filter/lib/Drupal/filter/Tests/FilterUnitTest.php
index de9f194..b2264a4 100644
--- a/core/modules/filter/lib/Drupal/filter/Tests/FilterUnitTest.php
+++ b/core/modules/filter/lib/Drupal/filter/Tests/FilterUnitTest.php
@@ -981,9 +981,9 @@ function testHtmlCorrectorFilter() {
    * @param $needle
    *   Lowercase, plain text to look for.
    * @param $message
-   *   (optional) Message to display if failed. Defaults to an empty string.
+   *   Message to display if failed.
    * @param $group
-   *   (optional) The group this message belongs to. Defaults to 'Other'.
+   *   The group this message belongs to, defaults to 'Other'.
    * @return
    *   TRUE on pass, FALSE on fail.
    */
@@ -1005,9 +1005,9 @@ function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
    * @param $needle
    *   Lowercase, plain text to look for.
    * @param $message
-   *   (optional) Message to display if failed. Defaults to an empty string.
+   *   Message to display if failed.
    * @param $group
-   *   (optional) The group this message belongs to. Defaults to 'Other'.
+   *   The group this message belongs to, defaults to 'Other'.
    * @return
    *   TRUE on pass, FALSE on fail.
    */
diff --git a/core/modules/menu/config/menu.menu.account.yml b/core/modules/menu/config/menu.menu.account.yml
deleted file mode 100644
index 6be2706..0000000
--- a/core/modules/menu/config/menu.menu.account.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-id: account
-label: User account menu
-description: Links related to the user account.
diff --git a/core/modules/menu/config/menu.menu.admin.yml b/core/modules/menu/config/menu.menu.admin.yml
deleted file mode 100644
index 5435da5..0000000
--- a/core/modules/menu/config/menu.menu.admin.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-id: admin
-label: Administration
-description: Contains links to administrative tasks.
diff --git a/core/modules/menu/config/menu.menu.footer.yml b/core/modules/menu/config/menu.menu.footer.yml
deleted file mode 100644
index 9dda784..0000000
--- a/core/modules/menu/config/menu.menu.footer.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-id: footer
-label: Footer
-description: Use this for linking to site information.
diff --git a/core/modules/menu/config/menu.menu.main.yml b/core/modules/menu/config/menu.menu.main.yml
deleted file mode 100644
index 3dfe975..0000000
--- a/core/modules/menu/config/menu.menu.main.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-id: main
-label: Main navigation
-description: Use this for linking to the main site sections.
diff --git a/core/modules/menu/config/menu.menu.tools.yml b/core/modules/menu/config/menu.menu.tools.yml
deleted file mode 100644
index 3f15287..0000000
--- a/core/modules/menu/config/menu.menu.tools.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-id: tools
-label: Tools
-description: Contains links for site visitors. Some modules add their links here.
diff --git a/core/modules/menu/lib/Drupal/menu/MenuFormController.php b/core/modules/menu/lib/Drupal/menu/MenuFormController.php
deleted file mode 100644
index 41e5696..0000000
--- a/core/modules/menu/lib/Drupal/menu/MenuFormController.php
+++ /dev/null
@@ -1,103 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains Drupal\menu\MenuFormController.
- */
-
-namespace Drupal\menu;
-
-use Drupal\Core\Entity\EntityInterface;
-use Drupal\Core\Entity\EntityFormController;
-
-/**
- * Base form controller for menu edit forms.
- */
-class MenuFormController extends EntityFormController {
-
-  /**
-   * Overrides Drupal\Core\Entity\EntityFormController::form().
-   */
-  public function form(array $form, array &$form_state, EntityInterface $menu) {
-    $form = parent::form($form, $form_state, $menu);
-    $system_menus = menu_list_system_menus();
-
-    $form['label'] = array(
-      '#type' => 'textfield',
-      '#title' => t('Title'),
-      '#default_value' => $menu->label(),
-      '#required' => TRUE,
-      // The title of a system menu cannot be altered.
-      '#access' => !isset($system_menus[$menu->id()]),
-    );
-    $form['id'] = array(
-      '#type' => 'machine_name',
-      '#title' => t('Menu name'),
-      '#default_value' => $menu->id(),
-      '#maxlength' => MENU_MAX_MENU_NAME_LENGTH_UI,
-      '#description' => t('A unique name to construct the URL for the menu. It must only contain lowercase letters, numbers and hyphens.'),
-      '#machine_name' => array(
-        'exists' => 'menu_edit_menu_name_exists',
-        'source' => array('label'),
-        'replace_pattern' => '[^a-z0-9-]+',
-        'replace' => '-',
-      ),
-      // A menu's machine name cannot be changed.
-      '#disabled' => !$menu->isNew() || isset($system_menus[$menu->id()]),
-    );
-    $form['description'] = array(
-      '#type' => 'textarea',
-      '#title' => t('Description'),
-      '#default_value' => $menu->description,
-    );
-    $form['actions'] = array('#type' => 'actions');
-    $form['actions']['submit'] = array(
-      '#type' => 'submit',
-      '#value' => t('Save'),
-      '#button_type' => 'primary',
-    );
-    // Only custom menus may be deleted.
-    $form['actions']['delete'] = array(
-      '#type' => 'submit',
-      '#value' => t('Delete'),
-      '#access' => !$menu->isNew() && !isset($system_menus[$menu->id()]),
-    );
-
-    return $form;
-  }
-
-  /**
-   * Overrides Drupal\Core\Entity\EntityFormController::save().
-   */
-  public function save(array $form, array &$form_state) {
-    $menu = $this->getEntity($form_state);
-
-    if ($menu->isNew()) {
-      // Add 'menu-' to the menu name to help avoid name-space conflicts.
-      $menu->set('id', 'menu-' . $menu->id());
-    }
-
-    $status = $menu->save();
-
-    $uri = $menu->uri();
-    if ($status == SAVED_UPDATED) {
-      drupal_set_message(t('Menu %label has been updated.', array('%label' => $menu->label())));
-      watchdog('menu', 'Menu %label has been updated.', array('%label' => $menu->label()), WATCHDOG_NOTICE, l(t('Edit'), $uri['path'] . '/edit'));
-    }
-    else {
-      drupal_set_message(t('Menu %label has been added.', array('%label' => $menu->label())));
-      watchdog('menu', 'Menu %label has been added.', array('%label' => $menu->label()), WATCHDOG_NOTICE, l(t('Edit'), $uri['path'] . '/edit'));
-    }
-
-    $form_state['redirect'] = 'admin/structure/menu/manage/' . $menu->id();
-  }
-
-  /**
-   * Overrides Drupal\Core\Entity\EntityFormController::delete().
-   */
-  public function delete(array $form, array &$form_state) {
-    $menu = $this->getEntity($form_state);
-    $form_state['redirect'] = 'admin/structure/menu/manage/' . $menu->id() . '/delete';
-  }
-
-}
diff --git a/core/modules/menu/lib/Drupal/menu/MenuListController.php b/core/modules/menu/lib/Drupal/menu/MenuListController.php
deleted file mode 100644
index a833dbc..0000000
--- a/core/modules/menu/lib/Drupal/menu/MenuListController.php
+++ /dev/null
@@ -1,83 +0,0 @@
-<?php
-
-/**
- * Contains \Drupal\menu\MenuListController.
- */
-
-namespace Drupal\menu;
-
-use Drupal\Core\Config\Entity\ConfigEntityListController;
-use Drupal\Core\Entity\EntityInterface;
-
-/**
- * Provides a listing of contact categories.
- */
-class MenuListController extends ConfigEntityListController {
-
-  /**
-   * Overrides \Drupal\Core\Entity\EntityListController::buildHeader().
-   */
-  public function buildHeader() {
-    $row['title'] = t('Title');
-    $row['description'] = array(
-      'data' => t('Description'),
-      'class' => array(RESPONSIVE_PRIORITY_MEDIUM),
-    );
-    $row['operations'] = t('Operations');
-    return $row;
-  }
-
-  /**
-   * Overrides \Drupal\Core\Entity\EntityListController::buildRow().
-   */
-  public function buildRow(EntityInterface $entity) {
-    $row['title'] = array(
-      'data' => check_plain($entity->label()),
-      'class' => array('menu-label'),
-    );
-    $row['description'] = filter_xss_admin($entity->description);
-    $row['operations']['data'] = $this->buildOperations($entity);
-    return $row;
-  }
-
-  /**
-   * Overrides \Drupal\Core\Entity\EntityListController::getOperations();
-   */
-  public function getOperations(EntityInterface $entity) {
-    $operations = parent::getOperations($entity);
-    $uri = $entity->uri();
-
-    $operations['list'] = array(
-      'title' => t('list links'),
-      'href' => $uri['path'],
-      'options' => $uri['options'],
-      'weight' => 0,
-    );
-    $operations['edit']['title'] = t('edit menu');
-    $operations['add'] = array(
-      'title' => t('add link'),
-      'href' => $uri['path'] . '/add',
-      'options' => $uri['options'],
-      'weight' => 20,
-    );
-    // System menus could not be deleted.
-    $system_menus = menu_list_system_menus();
-    if (isset($system_menus[$entity->id()])) {
-      unset($operations['delete']);
-    }
-    else {
-      $operations['delete']['title'] = t('delete menu');
-    }
-    return $operations;
-  }
-
-  /**
-   * Overrides \Drupal\Core\Entity\EntityListController::render();
-   */
-  public function render() {
-    $build = parent::render();
-    $build['#attached']['css'][] = drupal_get_path('module', 'menu') . '/menu.admin.css';
-    return $build;
-  }
-
-}
diff --git a/core/modules/menu/lib/Drupal/menu/Tests/MenuTest.php b/core/modules/menu/lib/Drupal/menu/Tests/MenuTest.php
index a0d8d28..caf27e6 100644
--- a/core/modules/menu/lib/Drupal/menu/Tests/MenuTest.php
+++ b/core/modules/menu/lib/Drupal/menu/Tests/MenuTest.php
@@ -102,8 +102,8 @@ function doStandardMenuTests() {
    */
   function doCustomMenuTests() {
     $this->menu = $this->addCustomMenu();
-    $this->doMenuTests($this->menu->id());
-    $this->addInvalidMenuLink($this->menu->id());
+    $this->doMenuTests($this->menu['menu_name']);
+    $this->addInvalidMenuLink($this->menu['menu_name']);
     $this->addCustomMenuCRUD();
   }
 
@@ -113,25 +113,25 @@ function doCustomMenuTests() {
   function addCustomMenuCRUD() {
     // Add a new custom menu.
     $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI);
-    $label = $this->randomName(16);
+    $title = $this->randomName(16);
 
-    $menu = entity_create('menu', array(
-      'id' => $menu_name,
-      'label' => $label,
+    $menu = array(
+      'menu_name' => $menu_name,
+      'title' => $title,
       'description' => 'Description text',
-    ));
-    $menu->save();
+    );
+    menu_save($menu);
 
     // Assert the new menu.
     $this->drupalGet('admin/structure/menu/manage/' . $menu_name . '/edit');
-    $this->assertRaw($label, 'Custom menu was added.');
+    $this->assertRaw($title, 'Custom menu was added.');
 
     // Edit the menu.
-    $new_label = $this->randomName(16);
-    $menu->set('label', $new_label);
-    $menu->save();
+    $new_title = $this->randomName(16);
+    $menu['title'] = $new_title;
+    menu_save($menu);
     $this->drupalGet('admin/structure/menu/manage/' . $menu_name . '/edit');
-    $this->assertRaw($new_label, 'Custom menu was edited.');
+    $this->assertRaw($new_title, 'Custom menu was edited.');
   }
 
   /**
@@ -142,11 +142,11 @@ function addCustomMenu() {
     // Try adding a menu using a menu_name that is too long.
     $this->drupalGet('admin/structure/menu/add');
     $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI + 1);
-    $label = $this->randomName(16);
+    $title = $this->randomName(16);
     $edit = array(
-      'id' => $menu_name,
+      'menu_name' => $menu_name,
       'description' => '',
-      'label' =>  $label,
+      'title' =>  $title,
     );
     $this->drupalPost('admin/structure/menu/add', $edit, t('Save'));
 
@@ -159,7 +159,7 @@ function addCustomMenu() {
 
     // Change the menu_name so it no longer exceeds the maximum length.
     $menu_name = substr(hash('sha256', $this->randomName(16)), 0, MENU_MAX_MENU_NAME_LENGTH_UI);
-    $edit['id'] = $menu_name;
+    $edit['menu_name'] = $menu_name;
     $this->drupalPost('admin/structure/menu/add', $edit, t('Save'));
 
     // Verify that no validation error is given for menu_name length.
@@ -168,16 +168,16 @@ function addCustomMenu() {
       '%max' => MENU_MAX_MENU_NAME_LENGTH_UI,
       '%length' => drupal_strlen($menu_name),
     )));
-    // Verify that confirmation message displayed.
-    $this->assertRaw(t('Menu %label has been added.', array('%label' => $label)));
+    // Unlike most other modules, there is no confirmation message displayed.
+
     $this->drupalGet('admin/structure/menu');
-    $this->assertText($label, 'Menu created');
+    $this->assertText($title, 'Menu created');
 
     // Enable the custom menu block.
     $menu_name = 'menu-' . $menu_name; // Drupal prepends the name with 'menu-'.
     // Confirm that the custom menu block is available.
     $this->drupalGet('admin/structure/block/list/block_plugin_ui:' . variable_get('theme_default', 'stark') . '/add');
-    $this->assertText($label);
+    $this->assertText($title);
 
     // Enable the block.
     $this->drupalPlaceBlock('menu_menu_block:' . $menu_name);
@@ -190,13 +190,13 @@ function addCustomMenu() {
    * @param string $menu_name Custom menu name.
    */
   function deleteCustomMenu($menu) {
-    $menu_name = $this->menu->id();
-    $label = $this->menu->label();
+    $menu_name = $this->menu['menu_name'];
+    $title = $this->menu['title'];
 
     // Delete custom menu.
     $this->drupalPost("admin/structure/menu/manage/$menu_name/delete", array(), t('Delete'));
     $this->assertResponse(200);
-    $this->assertRaw(t('The custom menu %title has been deleted.', array('%title' => $label)), 'Custom menu was deleted');
+    $this->assertRaw(t('The custom menu %title has been deleted.', array('%title' => $title)), 'Custom menu was deleted');
     $this->assertFalse(menu_load($menu_name), 'Custom menu was deleted');
     // Test if all menu links associated to the menu were removed from database.
     $result = db_query("SELECT menu_name FROM {menu_links} WHERE menu_name = :menu_name", array(':menu_name' => $menu_name))->fetchField();
diff --git a/core/modules/menu/menu.admin.css b/core/modules/menu/menu.admin.css
index efbfe75..8717aca 100644
--- a/core/modules/menu/menu.admin.css
+++ b/core/modules/menu/menu.admin.css
@@ -1,6 +1,6 @@
+.menu-operations {
+  width: 100px;
+}
 .menu-enabled {
   width: 70px;
 }
-.menu-label {
-  font-weight: bold;
-}
diff --git a/core/modules/menu/menu.admin.inc b/core/modules/menu/menu.admin.inc
index 1962ce3..4a78495 100644
--- a/core/modules/menu/menu.admin.inc
+++ b/core/modules/menu/menu.admin.inc
@@ -6,42 +6,57 @@
  */
 
 use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
-use Drupal\system\Plugin\Core\Entity\Menu;
 
 /**
  * Menu callback which shows an overview page of all the custom menus and their descriptions.
  */
 function menu_overview_page() {
-  return entity_list_controller('menu')->render();
-}
+  $result = db_query("SELECT * FROM {menu_custom} ORDER BY title", array(), array('fetch' => PDO::FETCH_ASSOC));
+  $header = array(t('Title'), t('Operations'));
+  $rows = array();
+  foreach ($result as $menu) {
+    $row = array();
+    $row[] = theme('menu_admin_overview', array('title' => $menu['title'], 'name' => $menu['menu_name'], 'description' => $menu['description']));
+    $links = array();
+    $links['list'] = array(
+      'title' => t('list links'),
+      'href' => 'admin/structure/menu/manage/' . $menu['menu_name'],
+    );
+    $links['edit'] = array(
+      'title' => t('edit menu'),
+      'href' => 'admin/structure/menu/manage/' . $menu['menu_name'] . '/edit',
+    );
+    $links['add'] = array(
+      'title' => t('add link'),
+      'href' => 'admin/structure/menu/manage/' . $menu['menu_name'] . '/add',
+    );
+    $row[] = array(
+      'data' => array(
+        '#type' => 'operations',
+        '#links' => $links,
+      ),
+    );
+    $rows[] = $row;
+  }
 
-/**
- * Page callback: Presents the menu creation form.
- *
- * @return array
- *   A form array as expected by drupal_render().
- *
- * @see menu_menu()
- */
-function menu_menu_add() {
-  $menu = entity_create('menu', array());
-  return entity_get_form($menu);
+  return theme('table', array('header' => $header, 'rows' => $rows));
 }
 
 /**
- * Page callback: Presents the menu edit form.
- *
- * @param \Drupal\system\Plugin\Core\Entity\Menu $menu
- *   The menu to edit.
+ * Returns HTML for a menu title and description for the menu overview page.
  *
- * @return array
- *   A form array as expected by drupal_render().
+ * @param $variables
+ *   An associative array containing:
+ *   - title: The menu's title.
+ *   - description: The menu's description.
  *
- * @see menu_menu()
+ * @ingroup themeable
  */
-function menu_menu_edit(Menu $menu) {
-  drupal_set_title(t('Edit menu %label', array('%label' => $menu->label())), PASS_THROUGH);
-  return entity_get_form($menu);
+function theme_menu_admin_overview($variables) {
+  $output = check_plain($variables['title']);
+  $output .= '<div class="description">' . filter_xss_admin($variables['description']) . '</div>';
+
+  return $output;
 }
 
 /**
@@ -58,7 +73,7 @@ function menu_overview_form($form, &$form_state, $menu) {
     FROM {menu_links} ml LEFT JOIN {menu_router} m ON m.path = ml.router_path
     WHERE ml.menu_name = :menu
     ORDER BY p1 ASC, p2 ASC, p3 ASC, p4 ASC, p5 ASC, p6 ASC, p7 ASC, p8 ASC, p9 ASC";
-  $result = db_query($sql, array(':menu' => $menu->id()), array('fetch' => PDO::FETCH_ASSOC));
+  $result = db_query($sql, array(':menu' => $menu['menu_name']), array('fetch' => PDO::FETCH_ASSOC));
   $links = array();
   foreach ($result as $item) {
     $links[] = $item;
@@ -84,7 +99,7 @@ function menu_overview_form($form, &$form_state, $menu) {
     );
   }
   else {
-    $form['#empty_text'] = t('There are no menu links yet. <a href="@link">Add link</a>.', array('@link' => url('admin/structure/menu/manage/'. $form['#menu']->id() .'/add')));
+    $form['#empty_text'] = t('There are no menu links yet. <a href="@link">Add link</a>.', array('@link' => url('admin/structure/menu/manage/'. $form['#menu']['menu_name'] .'/add')));
   }
   return $form;
 }
@@ -281,7 +296,7 @@ function theme_menu_overview_form($variables) {
 function menu_edit_item($form, &$form_state, $type, $item, $menu) {
   if ($type == 'add' || empty($item)) {
     // This is an add form, initialize the menu link.
-    $item = array('link_title' => '', 'mlid' => 0, 'plid' => 0, 'menu_name' => $menu->id(), 'weight' => 0, 'link_path' => '', 'options' => array(), 'module' => 'menu', 'expanded' => 0, 'hidden' => 0, 'has_children' => 0);
+    $item = array('link_title' => '', 'mlid' => 0, 'plid' => 0, 'menu_name' => $menu['menu_name'], 'weight' => 0, 'link_path' => '', 'options' => array(), 'module' => 'menu', 'expanded' => 0, 'hidden' => 0, 'has_children' => 0);
   }
   else {
     // Get the human-readable menu title from the given menu name.
@@ -463,12 +478,85 @@ function menu_edit_item_submit($form, &$form_state) {
 }
 
 /**
+ * Menu callback; Build the form that handles the adding/editing of a custom menu.
+ */
+function menu_edit_menu($form, &$form_state, $type, $menu = array()) {
+  $system_menus = menu_list_system_menus();
+  $menu += array(
+    'menu_name' => '',
+    'old_name' => !empty($menu['menu_name']) ? $menu['menu_name'] : '',
+    'title' => '',
+    'description' => '',
+  );
+  // Allow menu_edit_menu_submit() and other form submit handlers to determine
+  // whether the menu already exists.
+  $form['#insert'] = empty($menu['old_name']);
+  $form['old_name'] = array(
+    '#type' => 'value',
+    '#value' => $menu['old_name'],
+  );
+
+  $form['title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Title'),
+    '#default_value' => $menu['title'],
+    '#required' => TRUE,
+    // The title of a system menu cannot be altered.
+    '#access' => !isset($system_menus[$menu['menu_name']]),
+  );
+
+  $form['menu_name'] = array(
+    '#type' => 'machine_name',
+    '#title' => t('Menu name'),
+    '#default_value' => $menu['menu_name'],
+    '#maxlength' => MENU_MAX_MENU_NAME_LENGTH_UI,
+    '#description' => t('A unique name to construct the URL for the menu. It must only contain lowercase letters, numbers and hyphens.'),
+    '#machine_name' => array(
+      'exists' => 'menu_edit_menu_name_exists',
+      'source' => array('title'),
+      'replace_pattern' => '[^a-z0-9-]+',
+      'replace' => '-',
+    ),
+    // A menu's machine name cannot be changed.
+    '#disabled' => !empty($menu['old_name']) || isset($system_menus[$menu['menu_name']]),
+  );
+
+  $form['description'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Description'),
+    '#default_value' => $menu['description'],
+  );
+  $form['actions'] = array('#type' => 'actions');
+  $form['actions']['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Save'),
+    '#button_type' => 'primary',
+  );
+  // Only custom menus may be deleted.
+  $form['actions']['delete'] = array(
+    '#type' => 'submit',
+    '#value' => t('Delete'),
+    '#access' => $type == 'edit' && !isset($system_menus[$menu['menu_name']]),
+    '#submit' => array('menu_custom_delete_submit'),
+  );
+
+  return $form;
+}
+
+/**
+ * Submit function for the 'Delete' button on the menu editing form.
+ */
+function menu_custom_delete_submit($form, &$form_state) {
+  $form_state['redirect'] = 'admin/structure/menu/manage/' . $form_state['values']['menu_name'] . '/delete';
+}
+
+/**
  * Menu callback; check access and get a confirm form for deletion of a custom menu.
  */
 function menu_delete_menu_page($menu) {
   // System-defined menus may not be deleted.
   $system_menus = menu_list_system_menus();
-  if (isset($system_menus[$menu->id()])) {
+  if (isset($system_menus[$menu['menu_name']])) {
     throw new AccessDeniedHttpException();
   }
   return drupal_get_form('menu_delete_menu_confirm', $menu);
@@ -477,15 +565,15 @@ function menu_delete_menu_page($menu) {
 /**
  * Build a confirm form for deletion of a custom menu.
  */
-function menu_delete_menu_confirm($form, &$form_state, Menu $menu) {
+function menu_delete_menu_confirm($form, &$form_state, $menu) {
   $form['#menu'] = $menu;
   $caption = '';
-  $num_links = db_query("SELECT COUNT(*) FROM {menu_links} WHERE menu_name = :menu", array(':menu' => $menu->id()))->fetchField();
+  $num_links = db_query("SELECT COUNT(*) FROM {menu_links} WHERE menu_name = :menu", array(':menu' => $menu['menu_name']))->fetchField();
   if ($num_links) {
-    $caption .= '<p>' . format_plural($num_links, '<strong>Warning:</strong> There is currently 1 menu link in %title. It will be deleted (system-defined items will be reset).', '<strong>Warning:</strong> There are currently @count menu links in %title. They will be deleted (system-defined links will be reset).', array('%title' => $menu->label())) . '</p>';
+    $caption .= '<p>' . format_plural($num_links, '<strong>Warning:</strong> There is currently 1 menu link in %title. It will be deleted (system-defined items will be reset).', '<strong>Warning:</strong> There are currently @count menu links in %title. They will be deleted (system-defined links will be reset).', array('%title' => $menu['title'])) . '</p>';
   }
   $caption .= '<p>' . t('This action cannot be undone.') . '</p>';
-  return confirm_form($form, t('Are you sure you want to delete the custom menu %title?', array('%title' => $menu->label())), 'admin/structure/menu/manage/' . $menu->id(), $caption, t('Delete'));
+  return confirm_form($form, t('Are you sure you want to delete the custom menu %title?', array('%title' => $menu['title'])), 'admin/structure/menu/manage/' . $menu['menu_name'], $caption, t('Delete'));
 }
 
 /**
@@ -497,26 +585,26 @@ function menu_delete_menu_confirm_submit($form, &$form_state) {
 
   // System-defined menus may not be deleted - only menus defined by this module.
   $system_menus = menu_list_system_menus();
-  if (isset($system_menus[$menu->id()])) {
+  if (isset($system_menus[$menu['menu_name']])  || !(db_query("SELECT 1 FROM {menu_custom} WHERE menu_name = :menu", array(':menu' => $menu['menu_name']))->fetchField())) {
     return;
   }
 
   // Reset all the menu links defined by the system via hook_menu().
-  $result = db_query("SELECT * FROM {menu_links} ml INNER JOIN {menu_router} m ON ml.router_path = m.path WHERE ml.menu_name = :menu AND ml.module = 'system' ORDER BY m.number_parts ASC", array(':menu' => $menu->id()), array('fetch' => PDO::FETCH_ASSOC));
+  $result = db_query("SELECT * FROM {menu_links} ml INNER JOIN {menu_router} m ON ml.router_path = m.path WHERE ml.menu_name = :menu AND ml.module = 'system' ORDER BY m.number_parts ASC", array(':menu' => $menu['menu_name']), array('fetch' => PDO::FETCH_ASSOC));
   foreach ($result as $link) {
     menu_reset_item($link);
   }
 
   // Delete all links to the overview page for this menu.
-  $result = db_query("SELECT mlid FROM {menu_links} ml WHERE ml.link_path = :link", array(':link' => 'admin/structure/menu/manage/' . $menu->id()), array('fetch' => PDO::FETCH_ASSOC));
+  $result = db_query("SELECT mlid FROM {menu_links} ml WHERE ml.link_path = :link", array(':link' => 'admin/structure/menu/manage/' . $menu['menu_name']), array('fetch' => PDO::FETCH_ASSOC));
   foreach ($result as $link) {
     menu_link_delete($link['mlid']);
   }
 
   // Delete the custom menu and all its menu links.
-  $menu->delete();
+  menu_delete($menu);
 
-  $t_args = array('%title' => $menu->label());
+  $t_args = array('%title' => $menu['title']);
   drupal_set_message(t('The custom menu %title has been deleted.', $t_args));
   watchdog('menu', 'Deleted custom menu %title and all its menu links.', $t_args, WATCHDOG_NOTICE);
 }
@@ -528,9 +616,9 @@ function menu_delete_menu_confirm_submit($form, &$form_state) {
  * @see form_validate_machine_name()
  */
 function menu_edit_menu_name_exists($value) {
-  $custom_exists = entity_load('menu', $value);
   // 'menu-' is added to the menu name to avoid name-space conflicts.
   $value = 'menu-' . $value;
+  $custom_exists = db_query_range('SELECT 1 FROM {menu_custom} WHERE menu_name = :menu', 0, 1, array(':menu' => $value))->fetchField();
   $link_exists = db_query_range("SELECT 1 FROM {menu_links} WHERE menu_name = :menu", 0, 1, array(':menu' => $value))->fetchField();
 
   return $custom_exists || $link_exists;
@@ -544,9 +632,9 @@ function menu_edit_menu_submit($form, &$form_state) {
   $path = 'admin/structure/menu/manage/';
   if ($form['#insert']) {
     // Add 'menu-' to the menu name to help avoid name-space conflicts.
-    $menu['id'] = 'menu-' . $menu['id'];
-    $link['link_title'] = $menu['label'];
-    $link['link_path'] = $path . $menu['id'];
+    $menu['menu_name'] = 'menu-' . $menu['menu_name'];
+    $link['link_title'] = $menu['title'];
+    $link['link_path'] = $path . $menu['menu_name'];
     $link['router_path'] = $path . '%';
     $link['module'] = 'menu';
     $link['plid'] = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :link AND module = :module", array(
@@ -560,15 +648,15 @@ function menu_edit_menu_submit($form, &$form_state) {
   }
   else {
     menu_save($menu);
-    $result = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path", array(':path' => $path . $menu['id']), array('fetch' => PDO::FETCH_ASSOC));
+    $result = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path", array(':path' => $path . $menu['menu_name']), array('fetch' => PDO::FETCH_ASSOC));
     foreach ($result as $m) {
       $link = menu_link_load($m['mlid']);
-      $link['link_title'] = $menu['label'];
+      $link['link_title'] = $menu['title'];
       menu_link_save($link);
     }
   }
   drupal_set_message(t('Your configuration has been saved.'));
-  $form_state['redirect'] = $path . $menu['id'];
+  $form_state['redirect'] = $path . $menu['menu_name'];
 }
 
 /**
diff --git a/core/modules/menu/menu.api.php b/core/modules/menu/menu.api.php
index 95926a6..3f3818e 100644
--- a/core/modules/menu/menu.api.php
+++ b/core/modules/menu/menu.api.php
@@ -17,8 +17,11 @@
  * Contributed modules may use the information to perform actions based on the
  * information entered into the menu system.
  *
- * @param \Drupal\system\Plugin\Core\Entity\Menu $menu
- *   A menu entity.
+ * @param $menu
+ *   An array representing a custom menu:
+ *   - menu_name: The unique name of the custom menu.
+ *   - title: The human readable menu title.
+ *   - description: The custom menu description.
  *
  * @see hook_menu_update()
  * @see hook_menu_delete()
@@ -26,7 +29,7 @@
 function hook_menu_insert($menu) {
   // For example, we track available menus in a variable.
   $my_menus = variable_get('my_module_menus', array());
-  $my_menus[$menu->id()] = $menu->id();
+  $my_menus[$menu['menu_name']] = $menu['menu_name'];
   variable_set('my_module_menus', $my_menus);
 }
 
@@ -37,8 +40,13 @@ function hook_menu_insert($menu) {
  * Contributed modules may use the information to perform actions based on the
  * information entered into the menu system.
  *
- * @param \Drupal\system\Plugin\Core\Entity\Menu $menu
- *   A menu entity.
+ * @param $menu
+ *   An array representing a custom menu:
+ *   - menu_name: The unique name of the custom menu.
+ *   - title: The human readable menu title.
+ *   - description: The custom menu description.
+ *   - old_name: The current 'menu_name'. Note that internal menu names cannot
+ *     be changed after initial creation.
  *
  * @see hook_menu_insert()
  * @see hook_menu_delete()
@@ -46,7 +54,7 @@ function hook_menu_insert($menu) {
 function hook_menu_update($menu) {
   // For example, we track available menus in a variable.
   $my_menus = variable_get('my_module_menus', array());
-  $my_menus[$menu->id()] = $menu->id();
+  $my_menus[$menu['menu_name']] = $menu['menu_name'];
   variable_set('my_module_menus', $my_menus);
 }
 
@@ -58,8 +66,11 @@ function hook_menu_update($menu) {
  * information to perform actions based on the information entered into the menu
  * system.
  *
- * @param \Drupal\system\Plugin\Core\Entity\Menu $menu
- *   A menu entity.
+ * @param $link
+ *   An array representing a custom menu:
+ *   - menu_name: The unique name of the custom menu.
+ *   - title: The human readable menu title.
+ *   - description: The custom menu description.
  *
  * @see hook_menu_insert()
  * @see hook_menu_update()
@@ -67,7 +78,7 @@ function hook_menu_update($menu) {
 function hook_menu_delete($menu) {
   // Delete the record from our variable.
   $my_menus = variable_get('my_module_menus', array());
-  unset($my_menus[$menu->id()]);
+  unset($my_menus[$menu['menu_name']]);
   variable_set('my_module_menus', $my_menus);
 }
 
diff --git a/core/modules/menu/menu.install b/core/modules/menu/menu.install
index a76207b..f1a7b05 100644
--- a/core/modules/menu/menu.install
+++ b/core/modules/menu/menu.install
@@ -5,7 +5,63 @@
  * Install, update and uninstall functions for the menu module.
  */
 
-use Drupal\Component\Uuid\Uuid;
+/**
+ * Implements hook_schema().
+ */
+function menu_schema() {
+  $schema['menu_custom'] = array(
+    'description' => 'Holds definitions for top-level custom menus (for example, Main navigation menu).',
+    'fields' => array(
+      'menu_name' => array(
+        'type' => 'varchar',
+        'length' => 32,
+        'not null' => TRUE,
+        'default' => '',
+        'description' => 'Primary Key: Unique key for menu. This is used as a block delta so length is 32.',
+      ),
+      'title' => array(
+        'type' => 'varchar',
+        'length' => 255,
+        'not null' => TRUE,
+        'default' => '',
+        'description' => 'Menu title; displayed at top of block.',
+        'translatable' => TRUE,
+      ),
+      'description' => array(
+        'type' => 'text',
+        'not null' => FALSE,
+        'description' => 'Menu description.',
+        'translatable' => TRUE,
+      ),
+    ),
+    'primary key' => array('menu_name'),
+  );
+
+  return $schema;
+}
+
+/**
+ * Implements hook_install().
+ */
+function menu_install() {
+  $system_menus = menu_list_system_menus();
+  $t = get_t();
+  $descriptions = array(
+    'tools' => $t('Contains links for site visitors. Some modules add their links here.'),
+    'account' => $t('Links related to the user account.'),
+    'admin' => $t('Contains links to administrative tasks.'),
+    'main' => $t('Use this for linking to the main site sections.'),
+    'footer' => $t('Use this for linking to site information.'),
+  );
+  foreach ($system_menus as $menu_name => $title) {
+    $menu = array(
+      'menu_name' => $menu_name,
+      'title' => $t($title),
+      'description' => $descriptions[$menu_name],
+    );
+    menu_save($menu);
+  }
+}
 
 /**
  * Implements hook_uninstall().
@@ -70,22 +126,3 @@ function menu_update_8003() {
   ));
 }
 
-/**
- * Migrate menus into configuration.
- *
- * @ingroup config_upgrade
- */
-function menu_update_8004() {
-  $uuid = new Uuid();
-  $result = db_query('SELECT * FROM {menu_custom}');
-  foreach ($result as $menu) {
-    // Save the config object.
-    config('menu.menu.' . $menu->menu_name)
-      ->set('id', $menu->menu_name)
-      ->set('uuid', $uuid->generate())
-      ->set('label', $menu->title)
-      ->set('description', $menu->description)
-      ->save();
-    update_config_manifest_add('menu.menu', array($menu->menu_name));
-  }
-}
diff --git a/core/modules/menu/menu.module b/core/modules/menu/menu.module
index 3d4a360..ff24720 100644
--- a/core/modules/menu/menu.module
+++ b/core/modules/menu/menu.module
@@ -12,7 +12,6 @@
  */
 
 use Drupal\node\Plugin\Core\Entity\Node;
-use Drupal\system\Plugin\Core\Entity\Menu;
 use Drupal\system\Plugin\block\block\SystemMenuBlock;
 use Symfony\Component\HttpFoundation\JsonResponse;
 
@@ -83,7 +82,8 @@ function menu_menu() {
   );
   $items['admin/structure/menu/add'] = array(
     'title' => 'Add menu',
-    'page callback' => 'menu_menu_add',
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('menu_edit_menu', 'add'),
     'access arguments' => array('administer menu'),
     'type' => MENU_LOCAL_ACTION,
     'file' => 'menu.admin.inc',
@@ -101,7 +101,7 @@ function menu_menu() {
     'title' => 'Customize menu',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('menu_overview_form', 4),
-    'title callback' => 'entity_page_label',
+    'title callback' => 'menu_overview_title',
     'title arguments' => array(4),
     'access arguments' => array('administer menu'),
     'file' => 'menu.admin.inc',
@@ -122,8 +122,8 @@ function menu_menu() {
   );
   $items['admin/structure/menu/manage/%menu/edit'] = array(
     'title' => 'Edit menu',
-    'page callback' => 'menu_menu_edit',
-    'page arguments' => array(4),
+    'page callback' => 'drupal_get_form',
+    'page arguments' => array('menu_edit_menu', 'edit', 4),
     'access arguments' => array('administer menu'),
     'type' => MENU_LOCAL_TASK,
     'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
@@ -161,29 +161,6 @@ function menu_menu() {
 }
 
 /**
- * Implements hook_entity_info_alter().
- */
-function menu_entity_info_alter(&$entity_info) {
-  $entity_info['menu']['list_controller_class'] = 'Drupal\menu\MenuListController';
-  $entity_info['menu']['uri_callback'] = 'menu_uri';
-  $entity_info['menu']['form_controller_class'] = array(
-    'default' => 'Drupal\menu\MenuFormController',
-  );
-}
-
-/**
- * Entity URI callback.
- *
- * @param \Drupal\system\Plugin\Core\Entity\Menu $menu
- *   A Menu entity.
- */
-function menu_uri(Menu $menu) {
-  return array(
-    'path' => 'admin/structure/menu/manage/' . $menu->id(),
-  );
-}
-
-/**
  * Implements hook_theme().
  */
 function menu_theme() {
@@ -192,6 +169,10 @@ function menu_theme() {
       'file' => 'menu.admin.inc',
       'render element' => 'form',
     ),
+    'menu_admin_overview' => array(
+      'file' => 'menu.admin.inc',
+      'variables' => array('title' => NULL, 'name' => NULL, 'description' => NULL),
+    ),
   );
 }
 
@@ -205,13 +186,13 @@ function menu_enable() {
   $base_link = db_query("SELECT mlid AS plid, menu_name FROM {menu_links} WHERE link_path = 'admin/structure/menu' AND module = 'system'")->fetchAssoc();
   $base_link['router_path'] = 'admin/structure/menu/manage/%';
   $base_link['module'] = 'menu';
-  $menus = entity_load_multiple('menu');
-  foreach ($menus as $menu) {
+  $result = db_query("SELECT * FROM {menu_custom}", array(), array('fetch' => PDO::FETCH_ASSOC));
+  foreach ($result as $menu) {
     // $link is passed by reference to menu_link_save(), so we make a copy of $base_link.
     $link = $base_link;
     $link['mlid'] = 0;
-    $link['link_title'] = $menu->label();
-    $link['link_path'] = 'admin/structure/menu/manage/' . $menu->id();
+    $link['link_title'] = $menu['title'];
+    $link['link_path'] = 'admin/structure/menu/manage/' . $menu['menu_name'];
     $menu_link = db_query("SELECT mlid FROM {menu_links} WHERE link_path = :path AND plid = :plid", array(
       ':path' => $link['link_path'],
       ':plid' => $link['plid']
@@ -225,6 +206,13 @@ function menu_enable() {
 }
 
 /**
+ * Title callback for the menu overview page and links.
+ */
+function menu_overview_title($menu) {
+  return $menu['title'];
+}
+
+/**
  * Load the data for a single custom menu.
  *
  * @param $menu_name
@@ -233,69 +221,129 @@ function menu_enable() {
  *   Array defining the custom menu, or FALSE if the menu doesn't exist.
  */
 function menu_load($menu_name) {
-  return entity_load('menu', $menu_name);
+  $all_menus = menu_load_all();
+  return isset($all_menus[$menu_name]) ? $all_menus[$menu_name] : FALSE;
 }
 
 /**
- * Implements hook_menu_insert()
+ * Load all custom menu data.
+ *
+ * @return
+ *   Array of custom menu data.
  */
-function menu_menu_insert(Menu $menu) {
-  menu_cache_clear_all();
-  // Invalidate the block cache to update menu-based derivatives.
-  if (module_exists('block')) {
-    drupal_container()->get('plugin.manager.block')->clearCachedDefinitions();
-  }
-  // Make sure the menu is present in the active menus variable so that its
-  // items may appear in the menu active trail.
-  // See menu_set_active_menu_names().
-  $config = config('system.menu');
-
-  $active_menus = $config->get('active_menus_default') ?: array_keys(menu_get_menus());
-  if (!in_array($menu->id(), $active_menus)) {
-    $active_menus[] = $menu->id();
-    $config
-      ->set('active_menus_default', $active_menus)
-      ->save();
+function menu_load_all() {
+  $custom_menus = &drupal_static(__FUNCTION__);
+  if (!isset($custom_menus)) {
+    if ($cached = cache('menu')->get('menu_custom')) {
+      $custom_menus = $cached->data;
+    }
+    else {
+      $custom_menus = db_query('SELECT * FROM {menu_custom}')->fetchAllAssoc('menu_name', PDO::FETCH_ASSOC);
+      cache('menu')->set('menu_custom', $custom_menus);
+    }
   }
+  return $custom_menus;
 }
 
 /**
- * Implements hook_menu_update().
- */
-function menu_menu_update(Menu $menu) {
+ * Save a custom menu.
+ *
+ * @param $menu
+ *   An array representing a custom menu:
+ *   - menu_name: The unique name of the custom menu (composed of lowercase
+ *     letters, numbers, and hyphens).
+ *   - title: The human readable menu title.
+ *   - description: The custom menu description.
+ *
+ * Modules should always pass a fully populated $menu when saving a custom
+ * menu, so other modules are able to output proper status or watchdog messages.
+ *
+ * @see menu_load()
+ */
+function menu_save($menu) {
+  $status = db_merge('menu_custom')
+    ->key(array('menu_name' => $menu['menu_name']))
+    ->fields(array(
+      'title' => $menu['title'],
+      'description' => $menu['description'],
+    ))
+    ->execute();
   menu_cache_clear_all();
   // Invalidate the block cache to update menu-based derivatives.
   if (module_exists('block')) {
     drupal_container()->get('plugin.manager.block')->clearCachedDefinitions();
   }
+
+  switch ($status) {
+    case SAVED_NEW:
+      // Make sure the menu is present in the active menus variable so that its
+      // items may appear in the menu active trail.
+      // See menu_set_active_menu_names().
+      $config = config('system.menu');
+
+      $active_menus = $config->get('active_menus_default') ?: array_keys(menu_get_menus());
+      if (!in_array($menu['menu_name'], $active_menus)) {
+        $active_menus[] = $menu['menu_name'];
+        $config->set('active_menus_default', $active_menus);
+      }
+
+      module_invoke_all('menu_insert', $menu);
+      break;
+
+    case SAVED_UPDATED:
+      module_invoke_all('menu_update', $menu);
+      break;
+  }
 }
 
 /**
- * Implements hook_menu_predelete().
+ * Delete a custom menu and all contained links.
+ *
+ * Note that this function deletes all menu links in a custom menu. While menu
+ * links derived from router paths may be restored by rebuilding the menu, all
+ * customized and custom links will be irreversibly gone. Therefore, this
+ * function should usually be called from a user interface (form submit) handler
+ * only, which allows the user to confirm the action.
+ *
+ * @param $menu
+ *   An array representing a custom menu:
+ *   - menu_name: The unique name of the custom menu.
+ *   - title: The human readable menu title.
+ *   - description: The custom menu description.
+ *
+ * Modules should always pass a fully populated $menu when deleting a custom
+ * menu, so other modules are able to output proper status or watchdog messages.
+ *
+ * @see menu_load()
+ *
+ * menu_delete_links() will take care of clearing the page cache. Other modules
+ * should take care of their menu-related data by implementing
+ * hook_menu_delete().
  */
-function menu_menu_predelete(Menu $menu) {
+function menu_delete($menu) {
   // Delete all links from the menu.
-  menu_delete_links($menu->id());
+  menu_delete_links($menu['menu_name']);
 
   // Remove menu from active menus variable.
   $active_menus = variable_get('menu_default_active_menus', array_keys(menu_get_menus()));
   foreach ($active_menus as $i => $menu_name) {
-    if ($menu->id() == $menu_name) {
+    if ($menu['menu_name'] == $menu_name) {
       unset($active_menus[$i]);
       variable_set('menu_default_active_menus', $active_menus);
     }
   }
-}
 
-/**
- * Implements hook_menu_delete().
- */
-function menu_menu_delete(Menu $menu) {
+  // Delete the custom menu.
+  db_delete('menu_custom')
+    ->condition('menu_name', $menu['menu_name'])
+    ->execute();
+
   menu_cache_clear_all();
   // Invalidate the block cache to update menu-based derivatives.
   if (module_exists('block')) {
     drupal_container()->get('plugin.manager.block')->clearCachedDefinitions();
   }
+  module_invoke_all('menu_delete', $menu);
 }
 
 /**
@@ -730,12 +778,12 @@ function menu_form_node_type_form_alter(&$form, $form_state) {
  *   titles as the values.
  */
 function menu_get_menus($all = TRUE) {
-  if ($custom_menus = entity_load_multiple('menu')) {
+  if ($custom_menus = menu_load_all()) {
     if (!$all) {
       $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
     }
     foreach ($custom_menus as $menu_name => $menu) {
-      $custom_menus[$menu_name] = $menu->label();
+      $custom_menus[$menu_name] = t($menu['title']);
     }
     asort($custom_menus);
   }
diff --git a/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php b/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php
new file mode 100644
index 0000000..c785af9
--- /dev/null
+++ b/core/modules/node/lib/Drupal/node/Plugin/entity_reference/selection/NodeSelection.php
@@ -0,0 +1,44 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\node\Plugin\Type\selection\NodeSelection.
+ */
+
+namespace Drupal\node\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;
+
+/**
+ * Provides specific access control for the node entity type.
+ *
+ * @Plugin(
+ *   id = "base_node",
+ *   module = "entity_reference",
+ *   label = @Translation("Node selection"),
+ *   entity_types = {"node"},
+ *   group = "base",
+ *   weight = 1
+ * )
+ */
+class NodeSelection extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::buildEntityQuery().
+   */
+  public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = parent::buildEntityQuery($match, $match_operator);
+    // Adding the 'node_access' tag is sadly insufficient for nodes: core
+    // requires us to also know about the concept of 'published' and
+    // 'unpublished'. We need to do that as long as there are no access control
+    // modules in use on the site. As long as one access control module is there,
+    // it is supposed to handle this check.
+    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
+      $query->condition('status', NODE_PUBLISHED);
+    }
+    return $query;
+  }
+}
diff --git a/core/modules/options/options.module b/core/modules/options/options.module
index b49d16b..c692830 100644
--- a/core/modules/options/options.module
+++ b/core/modules/options/options.module
@@ -443,14 +443,14 @@ function options_field_widget_info() {
   return array(
     'options_select' => array(
       'label' => t('Select list'),
-      'field types' => array('list_integer', 'list_float', 'list_text'),
+      'field types' => array('list_integer', 'list_float', 'list_text', 'entity_reference'),
       'behaviors' => array(
         'multiple values' => FIELD_BEHAVIOR_CUSTOM,
       ),
     ),
     'options_buttons' => array(
       'label' => t('Check boxes/radio buttons'),
-      'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean'),
+      'field types' => array('list_integer', 'list_float', 'list_text', 'list_boolean', 'entity_reference'),
       'behaviors' => array(
         'multiple values' => FIELD_BEHAVIOR_CUSTOM,
       ),
diff --git a/core/modules/rdf/lib/Drupal/rdf/Tests/CommentAttributesTest.php b/core/modules/rdf/lib/Drupal/rdf/Tests/CommentAttributesTest.php
index 916dc95..fc883cb 100644
--- a/core/modules/rdf/lib/Drupal/rdf/Tests/CommentAttributesTest.php
+++ b/core/modules/rdf/lib/Drupal/rdf/Tests/CommentAttributesTest.php
@@ -123,7 +123,7 @@ public function testCommentRdfaMarkup() {
     // Tests comment #2 as anonymous user.
     $this->_testBasicCommentRdfaMarkup($comment2, $anonymous_user);
     // Tests the RDFa markup for the homepage (specific to anonymous comments).
-    $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name" and @datatype="" and @href="http://example.org/" and contains(@rel, "foaf:page")]');
+    $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name" and @href="http://example.org/" and contains(@rel, "foaf:page")]');
     $this->assertTrue(!empty($comment_homepage), 'RDFa markup for the homepage of anonymous user found.');
     // There should be no about attribute on anonymous comments.
     $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[@about]');
@@ -134,7 +134,7 @@ public function testCommentRdfaMarkup() {
     $this->drupalGet('node/' . $this->node2->nid);
     $this->_testBasicCommentRdfaMarkup($comment2, $anonymous_user);
     // Tests the RDFa markup for the homepage (specific to anonymous comments).
-    $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name" and @datatype="" and @href="http://example.org/" and contains(@rel, "foaf:page")]');
+    $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name" and @href="http://example.org/" and contains(@rel, "foaf:page")]');
     $this->assertTrue(!empty($comment_homepage), "RDFa markup for the homepage of anonymous user found.");
     // There should be no about attribute on anonymous comments.
     $comment_homepage = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/a[@about]');
@@ -185,7 +185,7 @@ function _testBasicCommentRdfaMarkup($comment, $account = array()) {
     $comment_date = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//*[contains(@property, "dc:date") and contains(@property, "dc:created")]');
     $this->assertTrue(!empty($comment_date), 'RDFa markup for the date of the comment found.');
     // The author tag can be either a or span
-    $comment_author = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/*[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name" and @datatype=""]');
+    $comment_author = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//span[@rel="sioc:has_creator"]/*[contains(@class, "username") and @typeof="sioc:UserAccount" and @property="foaf:name"]');
     $name = empty($account["name"]) ? $this->web_user->name : $account["name"] . " (not verified)";
     $this->assertEqual((string) $comment_author[0], $name, 'RDFa markup for the comment author found.');
     $comment_body = $this->xpath('//div[contains(@class, "comment") and contains(@typeof, "sioct:Comment")]//div[@class="content"]//div[contains(@class, "comment-body")]//div[@property="content:encoded"]');
diff --git a/core/modules/rdf/lib/Drupal/rdf/Tests/MappingDefinitionTest.php b/core/modules/rdf/lib/Drupal/rdf/Tests/MappingDefinitionTest.php
index 410a3e8..ab7fb0d 100644
--- a/core/modules/rdf/lib/Drupal/rdf/Tests/MappingDefinitionTest.php
+++ b/core/modules/rdf/lib/Drupal/rdf/Tests/MappingDefinitionTest.php
@@ -133,7 +133,7 @@ function testUserAttributesInMarkup() {
     $this->drupalGet('node/' . $node->nid);
     // Ensures the default bundle mapping for user is used on the Authored By
     // information on the node.
-    $author_about = $this->xpath('//a[@typeof="sioc:UserAccount" and @about=:account-uri and @property="foaf:name" and @datatype="" and contains(@lang, "")]', array(
+    $author_about = $this->xpath('//a[@typeof="sioc:UserAccount" and @about=:account-uri and @property="foaf:name" and contains(@lang, "")]', array(
       ':account-uri' => $account_uri,
     ));
     $this->assertTrue(!empty($author_about), 'RDFa markup found on author information on post. The lang attribute on username is set to empty string.');
diff --git a/core/modules/rdf/lib/Drupal/rdf/Tests/RdfaMarkupTest.php b/core/modules/rdf/lib/Drupal/rdf/Tests/RdfaMarkupTest.php
index 1c69a0e..368d221 100644
--- a/core/modules/rdf/lib/Drupal/rdf/Tests/RdfaMarkupTest.php
+++ b/core/modules/rdf/lib/Drupal/rdf/Tests/RdfaMarkupTest.php
@@ -174,12 +174,12 @@ function testAttributesInMarkupFile() {
     $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
     // Ensures the RDFa markup for the relationship between the node and its
     // tags is correct.
-    $term_rdfa_meta = $this->xpath('//div[@about=:node-url and contains(@typeof, "sioc:Item") and contains(@typeof, "foaf:Document")]//ul[@class="links"]/li[@rel="dc:subject"]/a[@typeof="skos:Concept" and @datatype="" and text()=:term-name]', array(
+    $term_rdfa_meta = $this->xpath('//div[@about=:node-url and contains(@typeof, "sioc:Item") and contains(@typeof, "foaf:Document")]//ul[@class="links"]/li[@rel="dc:subject"]/a[@typeof="skos:Concept" and text()=:term-name]', array(
       ':node-url' => url('node/' . $node->nid),
       ':term-name' => $tag1,
     ));
     $this->assertTrue(!empty($term_rdfa_meta), 'Property dc:subject is present for the tag1 field item.');
-    $term_rdfa_meta = $this->xpath('//div[@about=:node-url and contains(@typeof, "sioc:Item") and contains(@typeof, "foaf:Document")]//ul[@class="links"]/li[@rel="dc:subject"]/a[@typeof="skos:Concept" and @datatype="" and text()=:term-name]', array(
+    $term_rdfa_meta = $this->xpath('//div[@about=:node-url and contains(@typeof, "sioc:Item") and contains(@typeof, "foaf:Document")]//ul[@class="links"]/li[@rel="dc:subject"]/a[@typeof="skos:Concept" and text()=:term-name]', array(
       ':node-url' => url('node/' . $node->nid),
       ':term-name' => $tag2,
     ));
diff --git a/core/modules/rdf/rdf.module b/core/modules/rdf/rdf.module
index 55d89cb..ffc3a0b 100644
--- a/core/modules/rdf/rdf.module
+++ b/core/modules/rdf/rdf.module
@@ -679,12 +679,10 @@ function rdf_preprocess_username(&$variables) {
   if (!empty($rdf_mapping['rdftype'])) {
     $attributes['typeof'] = $rdf_mapping['rdftype'];
   }
-  // Annotate the username in RDFa. A property attribute is used with an empty
-  // datatype attribute to ensure the username is parsed as a plain literal
-  // in RDFa 1.0 and 1.1.
+  // Annotate the user name in RDFa. The property attribute is used here
+  // because the user name is a literal.
   if (!empty($rdf_mapping['name'])) {
     $attributes['property'] = $rdf_mapping['name']['predicates'];
-    $attributes['datatype'] = '';
   }
   // Add the homepage RDFa markup if present.
   if (!empty($variables['homepage']) && !empty($rdf_mapping['homepage'])) {
@@ -792,10 +790,7 @@ function rdf_field_attach_view_alter(&$output, $context) {
             $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
           }
           if (!empty($term->rdf_mapping['name']['predicates'])) {
-            // A property attribute is used with an empty datatype attribute so
-            // the term name is parsed as a plain literal in RDFa 1.0 and 1.1.
             $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
-            $element[$delta]['#options']['attributes']['datatype'] = '';
           }
         }
       }
diff --git a/core/modules/system/lib/Drupal/system/Plugin/Core/Entity/Menu.php b/core/modules/system/lib/Drupal/system/Plugin/Core/Entity/Menu.php
deleted file mode 100644
index 7e3ceb0..0000000
--- a/core/modules/system/lib/Drupal/system/Plugin/Core/Entity/Menu.php
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-
-/**
- * @file
- * Contains \Drupal\system\Plugin\Core\Entity\Menu.
- */
-
-namespace Drupal\system\Plugin\Core\Entity;
-
-use Drupal\Core\Config\Entity\ConfigEntityBase;
-use Drupal\Core\Annotation\Plugin;
-use Drupal\Core\Annotation\Translation;
-
-/**
- * Defines the Menu configuration entity class.
- *
- * @Plugin(
- *   id = "menu",
- *   label = @Translation("Menu"),
- *   module = "system",
- *   controller_class = "Drupal\Core\Config\Entity\ConfigStorageController",
- *   config_prefix = "menu.menu",
- *   entity_keys = {
- *     "id" = "id",
- *     "label" = "label",
- *     "uuid" = "uuid"
- *   }
- * )
- */
-class Menu extends ConfigEntityBase {
-
-  /**
-   * The menu machine name.
-   *
-   * @var string
-   */
-  public $id;
-
-  /**
-   * The menu UUID.
-   *
-   * @var string
-   */
-  public $uuid;
-
-  /**
-   * The human-readable name of the menu entity.
-   *
-   * @var string
-   */
-  public $label;
-
-  /**
-   * The menu description.
-   *
-   * @var string
-   */
-  public $description;
-
-}
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityCrudHookTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityCrudHookTest.php
index db722bb..91c292c 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityCrudHookTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityCrudHookTest.php
@@ -8,7 +8,6 @@
 namespace Drupal\system\Tests\Entity;
 
 use Drupal\simpletest\WebTestBase;
-use Drupal\Core\Database\Database;
 
 /**
  * Tests invocation of hooks when performing an action.
@@ -29,7 +28,7 @@ class EntityCrudHookTest extends WebTestBase {
    *
    * @var array
    */
-  public static $modules = array('entity_crud_hook_test', 'taxonomy', 'comment', 'file', 'entity_test');
+  public static $modules = array('entity_crud_hook_test', 'taxonomy', 'comment', 'file');
 
   protected $ids = array();
 
@@ -410,29 +409,4 @@ public function testUserHooks() {
       'entity_crud_hook_test_entity_delete called for type user',
     ));
   }
-
-  /**
-   * Tests rollback from failed insert in EntityNG.
-   */
-  function testEntityNGRollback() {
-    // Create a block.
-    try {
-      $entity = entity_create('entity_test', array('name' => 'fail_insert'))->save();
-      $this->fail('Expected exception has not been thrown.');
-    }
-    catch (\Exception $e) {
-      $this->pass('Expected exception has been thrown.');
-    }
-
-    if (Database::getConnection()->supportsTransactions()) {
-      // Check that the block does not exist in the database.
-      $ids = entity_query('entity_test')->condition('name', 'fail_insert')->execute();
-      $this->assertTrue(empty($ids), 'Transactions supported, and entity not found in database.');
-    }
-    else {
-      // Check that the block exists in the database.
-      $ids = entity_query('entity_test')->condition('name', 'fail_insert')->execute();
-      $this->assertFalse(empty($ids), 'Transactions not supported, and entity found in database.');
-    }
-  }
 }
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
index 19838f9..cb839dc 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityFieldTest.php
@@ -2,7 +2,7 @@
 
 /**
  * @file
- * Definition of Drupal\Core\Entity\Tests\EntityFieldTest.
+ * Definition of Drupal\system\Tests\Entity\EntityFieldTest.
  */
 
 namespace Drupal\system\Tests\Entity;
@@ -46,7 +46,7 @@ protected function createTestEntity() {
     // Pass in the value of the name field when creating. With the user
     // field we test setting a field after creation.
     $entity = entity_create('entity_test', array());
-    $entity->user_id->value = $this->entity_user->uid;
+    $entity->user_id->target_id = $this->entity_user->uid;
     $entity->name->value = $this->entity_name;
 
     // Set a value for the test field.
@@ -83,26 +83,26 @@ public function testReadWrite() {
     $this->assertTrue($entity->user_id instanceof FieldInterface, 'Field implements interface');
     $this->assertTrue($entity->user_id[0] instanceof FieldItemInterface, 'Field item implements interface');
 
-    $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.');
+    $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.');
     $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.');
 
     // Change the assigned user by entity.
     $new_user = $this->drupalCreateUser();
     $entity->user_id->entity = $new_user;
-    $this->assertEqual($new_user->uid, $entity->user_id->value, 'Updated user id can be read.');
+    $this->assertEqual($new_user->uid, $entity->user_id->target_id, 'Updated user id can be read.');
     $this->assertEqual($new_user->name, $entity->user_id->entity->name, 'Updated user name value can be read.');
 
     // Change the assigned user by id.
     $new_user = $this->drupalCreateUser();
-    $entity->user_id->value = $new_user->uid;
-    $this->assertEqual($new_user->uid, $entity->user_id->value, 'Updated user id can be read.');
+    $entity->user_id->target_id = $new_user->uid;
+    $this->assertEqual($new_user->uid, $entity->user_id->target_id, 'Updated user id can be read.');
     $this->assertEqual($new_user->name, $entity->user_id->entity->name, 'Updated user name value can be read.');
 
     // Try unsetting a field.
     $entity->name->value = NULL;
-    $entity->user_id->value = NULL;
+    $entity->user_id->target_id = NULL;
     $this->assertNull($entity->name->value, 'Name field is not set.');
-    $this->assertNull($entity->user_id->value, 'User ID field is not set.');
+    $this->assertNull($entity->user_id->target_id, 'User ID field is not set.');
     $this->assertNull($entity->user_id->entity, 'User entity field is not set.');
 
     // Test using isset(), empty() and unset().
@@ -173,7 +173,7 @@ public function testReadWrite() {
     $this->entity_name = $this->randomName();
     $name_item[0]['value'] = $this->entity_name;
     $this->entity_user = $this->drupalCreateUser();
-    $user_item[0]['value'] = $this->entity_user->uid;
+    $user_item[0]['target_id'] = $this->entity_user->uid;
     $this->entity_field_text = $this->randomName();
     $text_item[0]['value'] = $this->entity_field_text;
 
@@ -183,7 +183,7 @@ public function testReadWrite() {
       'field_test_text' => $text_item,
     ));
     $this->assertEqual($this->entity_name, $entity->name->value, 'Name value can be read.');
-    $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.');
+    $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.');
     $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.');
     $this->assertEqual($this->entity_field_text, $entity->field_test_text->value, 'Text field can be read.');
 
@@ -195,7 +195,7 @@ public function testReadWrite() {
 
     $this->assertTrue($entity->name !== $entity2->name, 'Copying properties results in a different field object.');
     $this->assertEqual($entity->name->value, $entity2->name->value, 'Name field copied.');
-    $this->assertEqual($entity->user_id->value, $entity2->user_id->value, 'User id field copied.');
+    $this->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, 'User id field copied.');
     $this->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, 'Text field copied.');
 
     // Tests adding a value to a field item list.
@@ -246,14 +246,14 @@ public function testReadWrite() {
     $this->assertEqual($entity->name->value, 'foo', 'Field value has been set via setPropertyValue() on an entity.');
 
     // Make sure the user id can be set to zero.
-    $user_item[0]['value'] = 0;
+    $user_item[0]['target_id'] = 0;
     $entity = entity_create('entity_test', array(
       'name' => $name_item,
       'user_id' => $user_item,
       'field_test_text' => $text_item,
     ));
-    $this->assertNotNull($entity->user_id->value, 'User id is not NULL');
-    $this->assertIdentical($entity->user_id->value, 0, 'User id has been set to 0');
+    $this->assertNotNull($entity->user_id->target_id, 'User id is not NULL');
+    $this->assertIdentical($entity->user_id->target_id, 0, 'User id has been set to 0');
 
     // Test setting the ID with the value only.
     $entity = entity_create('entity_test', array(
@@ -261,8 +261,8 @@ public function testReadWrite() {
       'user_id' => 0,
       'field_test_text' => $text_item,
     ));
-    $this->assertNotNull($entity->user_id->value, 'User id is not NULL');
-    $this->assertIdentical($entity->user_id->value, 0, 'User id has been set to 0');
+    $this->assertNotNull($entity->user_id->target_id, 'User id is not NULL');
+    $this->assertIdentical($entity->user_id->target_id, 0, 'User id has been set to 0');
   }
 
   /**
@@ -281,7 +281,7 @@ public function testSave() {
     $this->assertTrue(is_string($entity->uuid->value), 'UUID value can be read.');
     $this->assertEqual(LANGUAGE_NOT_SPECIFIED, $entity->langcode->value, 'Language code can be read.');
     $this->assertEqual(language_load(LANGUAGE_NOT_SPECIFIED), $entity->langcode->language, 'Language object can be read.');
-    $this->assertEqual($this->entity_user->uid, $entity->user_id->value, 'User id can be read.');
+    $this->assertEqual($this->entity_user->uid, $entity->user_id->target_id, 'User id can be read.');
     $this->assertEqual($this->entity_user->name, $entity->user_id->entity->name, 'User name can be read.');
     $this->assertEqual($this->entity_field_text, $entity->field_test_text->value, 'Text field can be read.');
   }
@@ -301,7 +301,7 @@ public function testIntrospection() {
     $wrapped_entity = typed_data()->create($definition);
     $definitions = $wrapped_entity->getPropertyDefinitions($definition);
     $this->assertEqual($definitions['name']['type'], 'string_field', 'Name field found.');
-    $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', 'User field found.');
+    $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', 'User field found.');
     $this->assertEqual($definitions['field_test_text']['type'], 'text_field', 'Test-text-field field found.');
 
     // Test introspecting an entity object.
@@ -310,14 +310,14 @@ public function testIntrospection() {
 
     $definitions = $entity->getPropertyDefinitions();
     $this->assertEqual($definitions['name']['type'], 'string_field', 'Name field found.');
-    $this->assertEqual($definitions['user_id']['type'], 'entityreference_field', 'User field found.');
+    $this->assertEqual($definitions['user_id']['type'], 'entity_reference_field', 'User field found.');
     $this->assertEqual($definitions['field_test_text']['type'], 'text_field', 'Test-text-field field found.');
 
     $name_properties = $entity->name->getPropertyDefinitions();
     $this->assertEqual($name_properties['value']['type'], 'string', 'String value property of the name found.');
 
     $userref_properties = $entity->user_id->getPropertyDefinitions();
-    $this->assertEqual($userref_properties['value']['type'], 'integer', 'Entity id property of the user found.');
+    $this->assertEqual($userref_properties['target_id']['type'], 'integer', 'Entity id property of the user found.');
     $this->assertEqual($userref_properties['entity']['type'], 'entity', 'Entity reference property of the user found.');
 
     $textfield_properties = $entity->field_test_text->getPropertyDefinitions();
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
index 4ca53c1..8d5fa81 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityQueryRelationshipTest.php
@@ -109,7 +109,7 @@ protected function setUp() {
       $entity = entity_create('entity_test', array());
       $entity->name->value = $this->randomName();
       $index = $i ? 1 : 0;
-      $entity->user_id->value = $this->accounts[$index]->uid;
+      $entity->user_id->target_id = $this->accounts[$index]->uid;
       $entity->{$this->fieldName}->tid = $this->terms[$index]->tid;
       $entity->save();
       $this->entities[] = $entity;
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
index 370622d..35995f7 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityTranslationTest.php
@@ -186,13 +186,13 @@ function testMultilingualProperties() {
     $entity = entity_test_load($entity->id());
     $this->assertEqual($entity->language()->langcode, LANGUAGE_NOT_SPECIFIED, 'Entity created as language neutral.');
     $this->assertEqual($name, $entity->getTranslation(LANGUAGE_DEFAULT)->get('name')->value, 'The entity name has been correctly stored as language neutral.');
-    $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->value, 'The entity author has been correctly stored as language neutral.');
+    $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_DEFAULT)->get('user_id')->target_id, 'The entity author has been correctly stored as language neutral.');
     // As fields, translatable properties should ignore the given langcode and
     // use neutral language if the entity is not translatable.
     $this->assertEqual($name, $entity->getTranslation($langcode)->get('name')->value, 'The entity name defaults to neutral language.');
-    $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, 'The entity author defaults to neutral language.');
+    $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, 'The entity author defaults to neutral language.');
     $this->assertEqual($name, $entity->get('name')->value, 'The entity name can be retrieved without specifying a language.');
-    $this->assertEqual($uid, $entity->get('user_id')->value, 'The entity author can be retrieved without specifying a language.');
+    $this->assertEqual($uid, $entity->get('user_id')->target_id, 'The entity author can be retrieved without specifying a language.');
 
     // Create a language-aware entity and check that properties are stored
     // as language-aware.
@@ -201,13 +201,13 @@ function testMultilingualProperties() {
     $entity = entity_test_load($entity->id());
     $this->assertEqual($entity->language()->langcode, $langcode, 'Entity created as language specific.');
     $this->assertEqual($name, $entity->getTranslation($langcode)->get('name')->value, 'The entity name has been correctly stored as a language-aware property.');
-    $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->value, 'The entity author has been correctly stored as a language-aware property.');
+    $this->assertEqual($uid, $entity->getTranslation($langcode)->get('user_id')->target_id, 'The entity author has been correctly stored as a language-aware property.');
     // Translatable properties on a translatable entity should use default
     // language if LANGUAGE_NOT_SPECIFIED is passed.
     $this->assertEqual($name, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('name')->value, 'The entity name defaults to the default language.');
-    $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->value, 'The entity author defaults to the default language.');
+    $this->assertEqual($uid, $entity->getTranslation(LANGUAGE_NOT_SPECIFIED)->get('user_id')->target_id, 'The entity author defaults to the default language.');
     $this->assertEqual($name, $entity->get('name')->value, 'The entity name can be retrieved without specifying a language.');
-    $this->assertEqual($uid, $entity->get('user_id')->value, 'The entity author can be retrieved without specifying a language.');
+    $this->assertEqual($uid, $entity->get('user_id')->target_id, 'The entity author can be retrieved without specifying a language.');
 
     // Create property translations.
     $properties = array();
@@ -234,7 +234,7 @@ function testMultilingualProperties() {
     foreach ($this->langcodes as $langcode) {
       $args = array('%langcode' => $langcode);
       $this->assertEqual($properties[$langcode]['name'][0], $entity->getTranslation($langcode)->get('name')->value, format_string('The entity name has been correctly stored for language %langcode.', $args));
-      $this->assertEqual($properties[$langcode]['user_id'][0], $entity->getTranslation($langcode)->get('user_id')->value, format_string('The entity author has been correctly stored for language %langcode.', $args));
+      $this->assertEqual($properties[$langcode]['user_id'][0], $entity->getTranslation($langcode)->get('user_id')->target_id, format_string('The entity author has been correctly stored for language %langcode.', $args));
     }
 
     // Test query conditions (cache is reset at each call).
diff --git a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
index cb2f7f3..88a2509 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Entity/EntityUUIDTest.php
@@ -81,7 +81,7 @@ function testCRUD() {
           $this->assertNotEqual($entity_duplicate->id(), $entity->id());
           break;
         default:
-          $this->assertEqual($entity_duplicate->{$property}->value, $entity->{$property}->value);
+          $this->assertEqual($entity_duplicate->{$property}->getValue(), $entity->{$property}->getValue());
       }
     }
     $entity_duplicate->save();
diff --git a/core/modules/system/lib/Drupal/system/Tests/Module/EnableDisableTest.php b/core/modules/system/lib/Drupal/system/Tests/Module/EnableDisableTest.php
index e8602f4..638c065 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Module/EnableDisableTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Module/EnableDisableTest.php
@@ -31,7 +31,7 @@ function testEnableDisable() {
       $in_testing_package = ($module->info['package'] == 'Testing');
       // Try to enable, disable and uninstall all core modules, unless they are
       // hidden or required or system test modules.
-      if (!$in_core_path || !empty($module->info['hidden']) || !empty($module->info['required']) || $in_testing_package) {
+      if (!$in_core_path || isset($module->info['hidden']) || isset($module->info['required']) || $in_testing_package) {
         unset($modules[$name]);
       }
     }
diff --git a/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php b/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
index f34cd9d..cc61e80 100644
--- a/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
+++ b/core/modules/system/lib/Drupal/system/Tests/Serialization/EntitySerializationTest.php
@@ -90,7 +90,7 @@ public function testNormalize() {
         array('value' => $this->values['name']),
       ),
       'user_id' => array(
-        array('value' => $this->values['user_id']),
+        array('target_id' => $this->values['user_id']),
       ),
       'field_test_text' => array(
         array(
diff --git a/core/modules/system/system.module b/core/modules/system/system.module
index e80a7df..6a5f48f 100644
--- a/core/modules/system/system.module
+++ b/core/modules/system/system.module
@@ -557,8 +557,7 @@ function system_element_info() {
   $types['vertical_tabs'] = array(
     '#default_tab' => '',
     '#process' => array('form_process_vertical_tabs'),
-    '#pre_render' => array('form_pre_render_vertical_tabs'),
-    '#theme_wrappers' => array('vertical_tabs', 'form_element'),
+    '#theme_wrappers' => array('vertical_tabs'),
   );
   $types['dropbutton'] = array(
     '#pre_render' => array('drupal_pre_render_dropbutton'),
@@ -2268,7 +2267,7 @@ function system_data_type_info() {
       'class' => '\Drupal\Core\Entity\Field\Type\LanguageItem',
       'list class' => '\Drupal\Core\Entity\Field\Type\Field',
     ),
-    'entityreference_field' => array(
+    'entity_reference_field' => array(
       'label' => t('Entity reference field item'),
       'description' => t('An entity field containing an entity reference.'),
       'class' => '\Drupal\Core\Entity\Field\Type\EntityReferenceItem',
diff --git a/core/modules/system/tests/modules/entity_test/entity_test.module b/core/modules/system/tests/modules/entity_test/entity_test.module
index 9063614..f2b5b38 100644
--- a/core/modules/system/tests/modules/entity_test/entity_test.module
+++ b/core/modules/system/tests/modules/entity_test/entity_test.module
@@ -169,12 +169,3 @@ function entity_test_form_node_form_alter(&$form, &$form_state, $form_id) {
   $langcode = $form_state['controller']->getFormLangcode($form_state);
   variable_set('entity_form_langcode', $langcode);
 }
-
-/**
- * Implements hook_ENTITY_TYPE_insert().
- */
-function entity_test_entity_test_insert($entity) {
-  if ($entity->name->value == 'fail_insert') {
-    throw new Exception("Test exception rollback.");
-  }
-}
diff --git a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
index a65f06f..561821c 100644
--- a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
+++ b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestFormController.php
@@ -36,7 +36,7 @@ public function form(array $form, array &$form_state, EntityInterface $entity) {
     $form['user_id'] = array(
       '#type' => 'textfield',
       '#title' => 'UID',
-      '#default_value' => $translation->user_id->value,
+      '#default_value' => $translation->user_id->target_id,
       '#size' => 60,
       '#maxlength' => 128,
       '#required' => TRUE,
diff --git a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
index d24ade8..bc80741 100644
--- a/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
+++ b/core/modules/system/tests/modules/entity_test/lib/Drupal/entity_test/EntityTestStorageController.php
@@ -54,7 +54,8 @@ protected function mapFromStorageRecords(array $records, $load_revision = FALSE)
       $values = isset($property_values[$id]) ? $property_values[$id] : array();
 
       foreach ($record as $name => $value) {
-        $values[$name][LANGUAGE_DEFAULT][0]['value'] = $value;
+        $key = $name == 'user_id' ? 'target_id' : 'value';
+        $values[$name][LANGUAGE_DEFAULT][0][$key] = $value;
       }
       $entity = new $this->entityClass($values, $this->entityType);
       $records[$id] = $entity;
@@ -88,7 +89,7 @@ protected function getPropertyValues($records, $load_revision = FALSE) {
       $langcode = empty($values['default_langcode']) ? $values['langcode'] : LANGUAGE_DEFAULT;
 
       $property_values[$id]['name'][$langcode][0]['value'] = $values['name'];
-      $property_values[$id]['user_id'][$langcode][0]['value'] = $values['user_id'];
+      $property_values[$id]['user_id'][$langcode][0]['target_id'] = $values['user_id'];
     }
     return $property_values;
   }
@@ -117,7 +118,7 @@ protected function postSave(EntityInterface $entity, $update) {
         'langcode' => $langcode,
         'default_langcode' => intval($default_langcode == $langcode),
         'name' => $translation->name->value,
-        'user_id' => $translation->user_id->value,
+        'user_id' => $translation->user_id->target_id,
       );
 
       $query
@@ -177,8 +178,8 @@ public function baseFieldDefinitions() {
     $fields['user_id'] = array(
       'label' => t('User ID'),
       'description' => t('The ID of the associated user.'),
-      'type' => 'entityreference_field',
-      'settings' => array('entity type' => 'user'),
+      'type' => 'entity_reference_field',
+      'settings' => array('target_type' => 'user'),
       'translatable' => TRUE,
     );
     return $fields;
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php
new file mode 100644
index 0000000..df87767
--- /dev/null
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/entity_reference/selection/TermSelection.php
@@ -0,0 +1,61 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\taxonomy\Plugin\entity_reference\selection\TermSelection.
+ */
+
+namespace Drupal\taxonomy\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;
+
+/**
+ * Provides specific access control for the taxonomy_term entity type.
+ *
+ * @Plugin(
+ *   id = "base_taxonomy_term",
+ *   module = "entity_reference",
+ *   label = @Translation("Taxonomy Term selection"),
+ *   entity_types = {"taxonomy_term"},
+ *   group = "base",
+ *   weight = 1
+ * )
+ */
+class TermSelection extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) {
+    // @todo: How to set access, as vocabulary is now config?
+  }
+
+  /**
+   * Overrides SelectionBase::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    if ($match || $limit) {
+      return parent::getReferencableEntities($match , $match_operator, $limit);
+    }
+
+    $options = array();
+
+    $entity_info = entity_get_info('taxonomy_term');
+    $bundles = !empty($this->instance['settings']['handler_settings']['target_bundles']) ? $this->instance['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
+
+    foreach ($bundles as $bundle) {
+      if ($vocabulary = entity_load('taxonomy_vocabulary',$bundle)) {
+        if ($terms = taxonomy_get_tree($vocabulary->id(), 0)) {
+          foreach ($terms as $term) {
+            $options[$vocabulary->id()][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
+          }
+        }
+      }
+    }
+
+    return $options;
+  }
+}
diff --git a/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php
new file mode 100644
index 0000000..c528985
--- /dev/null
+++ b/core/modules/taxonomy/lib/Drupal/taxonomy/Plugin/field/formatter/EntityReferenceTaxonomyTermRssFormatter.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\taxonomy\Plugin\field\formatter\EntityReferenceTaxonomyTermRssFormatter.
+ */
+
+namespace Drupal\taxonomy\Plugin\field\formatter;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase;
+
+/**
+ * Plugin implementation of the 'entity-reference taxonomy term RSS' formatter.
+ *
+ * @todo: Have a way to indicate this formatter applies only to taxonomy terms.
+ *
+ * @Plugin(
+ *   id = "entity_reference_rss_category",
+ *   module = "taxonomy",
+ *   label = @Translation("RSS category"),
+ *   description = @Translation("Display reference to taxonomy term in RSS."),
+ *   field_types = {
+ *     "entity_reference"
+ *   }
+ * )
+ */
+class EntityReferenceTaxonomyTermRssFormatter extends EntityReferenceFormatterBase {
+
+  /**
+   * Overrides Drupal\entity_reference\Plugin\field\formatter\EntityReferenceFormatterBase::viewElements().
+   */
+  public function viewElements(EntityInterface $entity, $langcode, array $items) {
+    $elements = array();
+
+    foreach ($items as $delta => $item) {
+      $entity->rss_elements[] = array(
+        'key' => 'category',
+        'value' => $item['target_id'] != 'autocreate' ? $item['entity']->label() : $item['label'],
+        'attributes' => array(
+          'domain' => $item['target_id'] != 'autocreate' ? url('taxonomy/term/' . $item['target_id'], array('absolute' => TRUE)) : '',
+        ),
+      );
+    }
+
+    return $elements;
+  }
+}
diff --git a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
index 6ad80a3..e55e95f 100644
--- a/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
+++ b/core/modules/translation_entity/lib/Drupal/translation_entity/Tests/EntityTranslationUITest.php
@@ -309,11 +309,12 @@ protected function getTranslation(EntityInterface $entity, $langcode) {
    *   The property value.
    */
   protected function getValue(ComplexDataInterface $translation, $property, $langcode) {
+    $key = $property == 'user_id' ? 'target_id' : 'value';
     if (($translation instanceof EntityInterface) && !($translation instanceof EntityNG)) {
-      return is_array($translation->$property) ? $translation->{$property}[$langcode][0]['value'] : $translation->$property;
+      return is_array($translation->$property) ? $translation->{$property}[$langcode][0][$key] : $translation->$property;
     }
     else {
-      return $translation->get($property)->value;
+      return $translation->get($property)->{$key};
     }
   }
 
diff --git a/core/modules/translation_entity/translation_entity.pages.inc b/core/modules/translation_entity/translation_entity.pages.inc
index 294c97b..385480b 100644
--- a/core/modules/translation_entity/translation_entity.pages.inc
+++ b/core/modules/translation_entity/translation_entity.pages.inc
@@ -209,9 +209,10 @@ function translation_entity_prepare_translation(EntityInterface $entity, Languag
     $source_translation = $entity->getTranslation($source->langcode);
     $target_translation = $entity->getTranslation($target->langcode);
     foreach ($target_translation->getPropertyDefinitions() as $property_name => $definition) {
-      // @todo The value part should not be needed. Remove it as soon as things
-      //   do not break.
-      $target_translation->$property_name->value = $source_translation->$property_name->value;
+      // @todo The "key" part should not be needed. Remove it as soon as things
+      // do not break.
+      $key = key($entity->{$property_name}[0]->getProperties());
+      $target_translation->$property_name->{$key} = $source_translation->$property_name->{$key};
     }
   }
   else {
diff --git a/core/modules/update/lib/Drupal/update/Tests/UpdateCoreTest.php b/core/modules/update/lib/Drupal/update/Tests/UpdateCoreTest.php
index 6c314d2..32dc111 100644
--- a/core/modules/update/lib/Drupal/update/Tests/UpdateCoreTest.php
+++ b/core/modules/update/lib/Drupal/update/Tests/UpdateCoreTest.php
@@ -17,7 +17,7 @@ class UpdateCoreTest extends UpdateTestBase {
    *
    * @var array
    */
-  public static $modules = array('update_test', 'update', 'language');
+  public static $modules = array('update_test', 'update');
 
   public static function getInfo() {
     return array(
@@ -33,7 +33,6 @@ function setUp() {
     $this->drupalLogin($admin_user);
   }
 
-
   /**
    * Tests the Update Manager module when no updates are available.
    */
@@ -219,19 +218,6 @@ function testFetchTasks() {
   }
 
   /**
-   * Checks language module in core package at admin/reports/updates.
-   */
-  function testLanguageModuleUpdate() {
-    $this->setSystemInfo7_0();
-    // Instead of using refreshUpdateStatus(), set these manually.
-    config('update.settings')->set('fetch.url', url('update-test', array('absolute' => TRUE)))->save();
-    config('update_test.settings')->set('xml_map', array('drupal' => '1'))->save();
-
-    $this->drupalGet('admin/reports/updates');
-    $this->assertText(t('Language'));
-  }
-
-  /**
    * Sets the version to 7.0 when no project-specific mapping is defined.
    */
   protected function setSystemInfo7_0() {
diff --git a/core/modules/update/update.compare.inc b/core/modules/update/update.compare.inc
index 59ce287..2262404 100644
--- a/core/modules/update/update.compare.inc
+++ b/core/modules/update/update.compare.inc
@@ -254,7 +254,7 @@ function update_get_project_name($file) {
   if (isset($file->info['project'])) {
     $project_name = $file->info['project'];
   }
-  elseif (isset($file->filename) && (strpos($file->filename, 'core/modules') === 0)) {
+  elseif (isset($file->info['package']) && (strpos($file->info['package'], 'Core') === 0)) {
     $project_name = 'drupal';
   }
   return $project_name;
diff --git a/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php b/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php
new file mode 100644
index 0000000..4a1352b
--- /dev/null
+++ b/core/modules/user/lib/Drupal/user/Plugin/entity_reference/selection/UserSelection.php
@@ -0,0 +1,146 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\user\Plugin\entity_reference\selection\UserSelection.
+ */
+
+namespace Drupal\user\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Database;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\entity_reference\Plugin\entity_reference\selection\SelectionBase;
+
+/**
+ * Provides specific access control for the user entity type.
+ *
+ * @Plugin(
+ *   id = "base_user",
+ *   module = "entity_reference",
+ *   label = @Translation("User selection"),
+ *   entity_types = {"user"},
+ *   group = "base",
+ *   weight = 1
+ * )
+ */
+class UserSelection extends SelectionBase {
+
+  /**
+   * Overrides SelectionBase::settingsForm().
+   */
+  public static function settingsForm(&$field, &$instance) {
+    $form = parent::settingsForm($field, $instance);
+
+    // Merge-in default values.
+    $instance['settings']['handler_settings'] += array(
+      'filter' => array(
+        'type' => '_none',
+      ),
+    );
+
+    // Add user specific filter options.
+    $form['filter']['type'] = array(
+      '#type' => 'select',
+      '#title' => t('Filter by'),
+      '#options' => array(
+        '_none' => t('- None -'),
+        'role' => t('User role'),
+      ),
+      '#ajax' => TRUE,
+      '#limit_validation_errors' => array(),
+      '#default_value' => $instance['settings']['handler_settings']['filter']['type'],
+    );
+
+    $form['filter']['settings'] = array(
+      '#type' => 'container',
+      '#attributes' => array('class' => array('entity_reference-settings')),
+      '#process' => array('_entity_reference_form_process_merge_parent'),
+    );
+
+    if ($instance['settings']['handler_settings']['filter']['type'] == 'role') {
+      // Merge-in default values.
+      $instance['settings']['handler_settings']['filter'] += array(
+        'role' => NULL,
+      );
+
+      $form['filter']['settings']['role'] = array(
+        '#type' => 'checkboxes',
+        '#title' => t('Restrict to the selected roles'),
+        '#required' => TRUE,
+        '#options' => user_roles(TRUE),
+        '#default_value' => $instance['settings']['handler_settings']['filter']['role'],
+      );
+    }
+
+    return $form;
+  }
+
+  /**
+   * Overrides SelectionBase::buildEntityQuery().
+   */
+  public function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
+    $query = parent::buildEntityQuery($match, $match_operator);
+
+    // The user entity doesn't have a label column.
+    if (isset($match)) {
+      $query->condition('name', $match, $match_operator);
+    }
+
+    // Adding the 'user_access' tag is sadly insufficient for users: core
+    // requires us to also know about the concept of 'blocked' and 'active'.
+    if (!user_access('administer users')) {
+      $query->condition('status', 1);
+    }
+    return $query;
+  }
+
+  /**
+   * Overrides SelectionBase::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) {
+    if (user_access('administer users')) {
+      // In addition, if the user is administrator, we need to make sure to
+      // match the anonymous user, that doesn't actually have a name in the
+      // database.
+      $conditions = &$query->conditions();
+      foreach ($conditions as $key => $condition) {
+        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
+          // Remove the condition.
+          unset($conditions[$key]);
+
+          // Re-add the condition and a condition on uid = 0 so that we end up
+          // with a query in the form:
+          // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
+          $or = db_or();
+          $or->condition($condition['field'], $condition['value'], $condition['operator']);
+          // Sadly, the Database layer doesn't allow us to build a condition
+          // in the form ':placeholder = :placeholder2', because the 'field'
+          // part of a condition is always escaped.
+          // As a (cheap) workaround, we separately build a condition with no
+          // field, and concatenate the field and the condition separately.
+          $value_part = db_and();
+          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
+          $value_part->compile(Database::getConnection(), $query);
+          $or->condition(db_and()
+            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name(user_load(0))))
+            ->condition('users.uid', 0)
+          );
+          $query->condition($or);
+        }
+      }
+    }
+
+    // Add the filter by role option.
+    if (!empty($this->instance['settings']['handler_settings']['filter'])) {
+      $filter_settings = $this->instance['settings']['handler_settings']['filter'];
+      if ($filter_settings['type'] == 'role') {
+        $tables = $query->getTables();
+        $base_table = $tables['base_table']['alias'];
+        $query->join('users_roles', 'ur', $base_table . '.uid = ur.uid');
+        $query->condition('ur.rid', $filter_settings['role']);
+      }
+    }
+  }
+}
diff --git a/core/modules/user/user.admin.inc b/core/modules/user/user.admin.inc
index 1689f62..dcd76d7 100644
--- a/core/modules/user/user.admin.inc
+++ b/core/modules/user/user.admin.inc
@@ -389,9 +389,12 @@ function user_admin_settings($form, &$form_state) {
     '#default_value' => $config->get('signatures'),
   );
 
+  $form['email_title'] = array(
+    '#type' => 'item',
+    '#title' => t('E-mails'),
+  );
   $form['email'] = array(
     '#type' => 'vertical_tabs',
-    '#title' => t('E-mails'),
   );
   // These email tokens are shared for all settings, so just define
   // the list once to help ensure they stay in sync.
diff --git a/core/modules/user/user.module b/core/modules/user/user.module
index 02f5072..bff000f 100644
--- a/core/modules/user/user.module
+++ b/core/modules/user/user.module
@@ -391,34 +391,36 @@ function user_password($length = 10) {
  *   An array indexed by role ID. Each value is an array whose keys are the
  *   permission strings for the given role ID.
  */
-function user_role_permissions($roles) {
+function user_role_permissions($roles = array()) {
   $cache = &drupal_static(__FUNCTION__, array());
 
   $role_permissions = $fetch = array();
 
-  foreach ($roles as $rid => $name) {
-    if (isset($cache[$rid])) {
-      $role_permissions[$rid] = $cache[$rid];
-    }
-    else {
-      // Add this rid to the list of those needing to be fetched.
-      $fetch[] = $rid;
-      // Prepare in case no permissions are returned.
-      $cache[$rid] = array();
+  if ($roles) {
+    foreach ($roles as $rid => $name) {
+      if (isset($cache[$rid])) {
+        $role_permissions[$rid] = $cache[$rid];
+      }
+      else {
+        // Add this rid to the list of those needing to be fetched.
+        $fetch[] = $rid;
+        // Prepare in case no permissions are returned.
+        $cache[$rid] = array();
+      }
     }
-  }
 
-  if ($fetch) {
-    // Get from the database permissions that were not in the static variable.
-    // Only role IDs with at least one permission assigned will return rows.
-    $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
+    if ($fetch) {
+      // Get from the database permissions that were not in the static variable.
+      // Only role IDs with at least one permission assigned will return rows.
+      $result = db_query("SELECT rid, permission FROM {role_permission} WHERE rid IN (:fetch)", array(':fetch' => $fetch));
 
-    foreach ($result as $row) {
-      $cache[$row->rid][$row->permission] = TRUE;
-    }
-    foreach ($fetch as $rid) {
-      // For every rid, we know we at least assigned an empty array.
-      $role_permissions[$rid] = $cache[$rid];
+      foreach ($result as $row) {
+        $cache[$row->rid][$row->permission] = TRUE;
+      }
+      foreach ($fetch as $rid) {
+        // For every rid, we know we at least assigned an empty array.
+        $role_permissions[$rid] = $cache[$rid];
+      }
     }
   }
 
diff --git a/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php
new file mode 100644
index 0000000..511c454
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/Plugin/entity_reference/selection/ViewsSelection.php
@@ -0,0 +1,229 @@
+<?php
+
+/**
+ * @file
+ * Contains Drupal\views\Plugin\entity_reference\selection\ViewsSelection.
+ */
+
+namespace Drupal\views\Plugin\entity_reference\selection;
+
+use Drupal\Core\Annotation\Plugin;
+use Drupal\Core\Annotation\Translation;
+use Drupal\Core\Database\Query\SelectInterface;
+use Drupal\Core\Entity\EntityInterface;
+use Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface;
+use Drupal\views\ViewsException;
+
+/**
+ * Plugin implementation of the 'selection' entity_reference.
+ *
+ * @Plugin(
+ *   id = "views",
+ *   module = "entity_reference",
+ *   label = @Translation("Views: Filter by an entity reference view"),
+ *   group = "views",
+ *   weight = 0
+ * )
+ */
+class ViewsSelection implements SelectionInterface {
+
+  /**
+   * The loaded View object.
+   *
+   * @var \Drupal\views\ViewExecutable;
+   */
+  protected $view;
+
+  /**
+   * Constructs a View selection handler.
+   */
+  public function __construct($field, $instance = NULL, EntityInterface $entity = NULL) {
+    $this->field = $field;
+    $this->instance = $instance;
+    $this->entity = $entity;
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::settingsForm().
+   */
+  public static function settingsForm(&$field, &$instance) {
+    $view_settings = empty($instance['settings']['handler_settings']['view']) ? array() : $instance['settings']['handler_settings']['view'];
+    $displays = views_get_applicable_views('entity_reference_display');
+    // Filter views that list the entity type we want, and group the separate
+    // displays by view.
+    $entity_info = entity_get_info($field['settings']['target_type']);
+    $options = array();
+    foreach ($displays as $data) {
+      list($view, $display_id) = $data;
+      if ($view->storage->get('base_table') == $entity_info['base_table']) {
+        $name = $view->storage->get('name');
+        $display = $view->storage->get('display');
+        $options[$name . ':' . $display_id] = $name . ' - ' . $display[$display_id]['display_title'];
+      }
+    }
+
+    // The value of the 'view_and_display' select below will need to be split
+    // into 'view_name' and 'view_display' in the final submitted values, so
+    // we massage the data at validate time on the wrapping element (not
+    // ideal).
+    $plugin = new static($field, $instance);
+    $form['view']['#element_validate'] = array(array($plugin, 'settingsFormValidate'));
+
+    if ($options) {
+      $default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
+      $form['view']['view_and_display'] = array(
+        '#type' => 'select',
+        '#title' => t('View used to select the entities'),
+        '#required' => TRUE,
+        '#options' => $options,
+        '#default_value' => $default,
+        '#description' => '<p>' . t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
+      );
+
+      $default = !empty($view_settings['arguments']) ? implode(', ', $view_settings['arguments']) : '';
+      $form['view']['arguments'] = array(
+        '#type' => 'textfield',
+        '#title' => t('View arguments'),
+        '#default_value' => $default,
+        '#required' => FALSE,
+        '#description' => t('Provide a comma separated list of arguments to pass to the view.'),
+      );
+    }
+    else {
+      $form['view']['no_view_help'] = array(
+        '#markup' => '<p>' . t('No eligible views were found. <a href="@create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href="@existing">existing view</a>.', array(
+          '@create' => url('admin/structure/views/add'),
+          '@existing' => url('admin/structure/views'),
+        )) . '</p>',
+      );
+    }
+    return $form;
+  }
+
+  /**
+   * Initializes a view.
+   *
+   * @param string|null $match
+   *   (Optional) Text to match the label against. Defaults to NULL.
+   * @param string $match_operator
+   *   (Optional) The operation the matching should be done with. Defaults
+   *   to "CONTAINS".
+   * @param int $limit
+   *   Limit the query to a given number of items. Defaults to 0, which
+   *   indicates no limiting.
+   * @param array|null $ids
+   *   Array of entity IDs. Defaults to NULL.
+   *
+   * @return bool
+   *   Return TRUE if the views was initialized, FALSE otherwise.
+   */
+  protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
+    $view_name = $this->instance['settings']['handler_settings']['view']['view_name'];
+    $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+    $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+    $entity_type = $this->field['settings']['target_type'];
+
+    // Check that the view is valid and the display still exists.
+    $this->view = views_get_view($view_name);
+    if (!$this->view  || !$this->view->access($display_name)) {
+      throw new ViewsException('The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']));
+    }
+    $this->view->setDisplay($display_name);
+
+    // Pass options to the display handler to make them available later.
+    $entity_reference_options = array(
+      'match' => $match,
+      'match_operator' => $match_operator,
+      'limit' => $limit,
+      'ids' => $ids,
+    );
+    $this->view->displayHandlers[$display_name]->setOption('entity_reference_options', $entity_reference_options);
+    return TRUE;
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::getReferencableEntities().
+   */
+  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
+    $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+    $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+    $result = array();
+    if ($this->initializeView($match, $match_operator, $limit)) {
+      // Get the results.
+      $result = $this->view->executeDisplay($display_name, $arguments);
+    }
+
+    $return = array();
+    if ($result) {
+      foreach($this->view->result as $row) {
+        $entity = $row->_entity;
+        $return[$entity->bundle()][$entity->id()] = $entity->label();
+      }
+    }
+    return $return;
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::countReferencableEntities().
+   */
+  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
+    $this->getReferencableEntities($match, $match_operator);
+    return $this->view->pager->get_total_items();
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::validateReferencableEntities().
+   */
+  public function validateReferencableEntities(array $ids) {
+    $display_name = $this->instance['settings']['handler_settings']['view']['display_name'];
+    $arguments = $this->instance['settings']['handler_settings']['view']['arguments'];
+    $result = array();
+    if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
+      // Get the results.
+      $entities = $this->view->executeDisplay($display_name, $arguments);
+      $result = array_keys($entities);
+    }
+    return $result;
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::validateAutocompleteInput().
+   */
+  public function validateAutocompleteInput($input, &$element, &$form_state, $form, $strict = TRUE) {
+    return NULL;
+  }
+
+  /**
+   * Implements Drupal\entity_reference\Plugin\Type\Selection\SelectionInterface::entityQueryAlter().
+   */
+  public function entityQueryAlter(SelectInterface $query) {}
+
+  /**
+   * Element validate; Check View is valid.
+   */
+  public function settingsFormValidate($element, &$form_state, $form) {
+    // Split view name and display name from the 'view_and_display' value.
+    if (!empty($element['view_and_display']['#value'])) {
+      list($view, $display) = explode(':', $element['view_and_display']['#value']);
+    }
+    else {
+      form_error($element, t('The views entity selection mode requires a view.'));
+      return;
+    }
+
+    // Explode the 'arguments' string into an actual array. Beware, explode() turns an
+    // empty string into an array with one empty string. We'll need an empty array
+    // instead.
+    $arguments_string = trim($element['arguments']['#value']);
+    if ($arguments_string === '') {
+      $arguments = array();
+    }
+    else {
+      // array_map is called to trim whitespaces from the arguments.
+      $arguments = array_map('trim', explode(',', $arguments_string));
+    }
+
+    $value = array('view_name' => $view, 'display_name' => $display, 'arguments' => $arguments);
+    form_set_value($element, $value, $form_state);
+  }
+}
diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/cache/CachePluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/cache/CachePluginBase.php
index 6cce4b0..ebae468 100644
--- a/core/modules/views/lib/Drupal/views/Plugin/views/cache/CachePluginBase.php
+++ b/core/modules/views/lib/Drupal/views/Plugin/views/cache/CachePluginBase.php
@@ -295,7 +295,7 @@ public function generateResultsKey() {
         }
       }
 
-      $this->resultsKey = $this->view->storage->get('name') . ':' . $this->displayHandler->display['id'] . ':results:' . hash('sha256', serialize($key_data));
+      $this->resultsKey = $this->view->storage->get('name') . ':' . $this->displayHandler->display['id'] . ':results:' . md5(serialize($key_data));
     }
 
     return $this->resultsKey;
@@ -319,7 +319,7 @@ public function generateOutputKey() {
         'base_url' => $GLOBALS['base_url'],
       );
 
-      $this->outputKey = $this->view->storage->get('name') . ':' . $this->displayHandler->display['id'] . ':output:' . hash('sha256', serialize($key_data));
+      $this->outputKey = $this->view->storage->get('name') . ':' . $this->displayHandler->display['id'] . ':output:' . md5(serialize($key_data));
     }
 
     return $this->outputKey;
diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php
index a9d79ba..06780c3 100644
--- a/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php
+++ b/core/modules/views/lib/Drupal/views/Plugin/views/display/DisplayPluginBase.php
@@ -130,7 +130,7 @@ public function initDisplay(ViewExecutable $view, array &$display, array &$optio
     // Cache for unpackOptions, but not if we are in the ui.
     static $unpack_options = array();
     if (empty($view->editing)) {
-      $cid = 'unpackOptions:' . hash('sha256', serialize(array($this->options, $options)));
+      $cid = 'unpackOptions:' . md5(serialize(array($this->options, $options)));
       if (empty($unpack_options[$cid])) {
         $cache = views_cache_get($cid, TRUE);
         if (!empty($cache->data)) {
diff --git a/core/modules/views/lib/Drupal/views/Plugin/views/style/StylePluginBase.php b/core/modules/views/lib/Drupal/views/Plugin/views/style/StylePluginBase.php
index 1fd2c22..d577365 100644
--- a/core/modules/views/lib/Drupal/views/Plugin/views/style/StylePluginBase.php
+++ b/core/modules/views/lib/Drupal/views/Plugin/views/style/StylePluginBase.php
@@ -556,7 +556,7 @@ function render_grouping($records, $groupings = array(), $group_rendered = NULL)
               // Not all field handlers return a scalar value,
               // e.g. views_handler_field_field.
               if (!is_scalar($grouping)) {
-                $grouping = hash('sha256', serialize($grouping));
+                $grouping = md5(serialize($grouping));
               }
             }
           }
diff --git a/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php b/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php
new file mode 100644
index 0000000..8e74d44
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/Tests/EntityReference/SelectionTest.php
@@ -0,0 +1,83 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\views\Tests\EntityReference\SelectionTest.
+ */
+
+namespace Drupal\views\Tests\EntityReference;
+
+use Drupal\simpletest\WebTestBase;
+
+/**
+ * Tests entity-reference selection handler.
+ */
+class SelectionTest extends WebTestBase {
+
+  public static $modules = array('views', 'entity_reference', 'entity_reference_test');
+
+  public static function getInfo() {
+    return array(
+      'name' => 'Entity reference selection handler',
+      'description' => 'Tests entity-reference selection handler provided by Views.',
+      'group' => 'Views',
+    );
+  }
+
+  /**
+   * Tests the selection handler.
+   */
+  public function testSelectionHandler() {
+    // Create nodes.
+    $type = $this->drupalCreateContentType()->type;
+    $node1 = $this->drupalCreateNode(array('type' => $type));
+    $node2 = $this->drupalCreateNode(array('type' => $type));
+    $node3 = $this->drupalCreateNode();
+
+    $nodes = array();
+    foreach (array($node1, $node2, $node3) as $node) {
+      $nodes[$node->type][$node->nid] = $node->label();
+    }
+
+    // Build a fake field instance.
+    $field = array(
+      'translatable' => FALSE,
+      'entity_types' => array(),
+      'settings' => array(
+        'target_type' => 'node',
+      ),
+      'field_name' => 'test_field',
+      'type' => 'entity_reference',
+      'cardinality' => '1',
+    );
+    $instance = array(
+      'settings' => array(
+        'handler' => 'views',
+        'handler_settings' => array(
+          'target_bundles' => array(),
+          'view' => array(
+            'view_name' => 'test_entity_reference',
+            'display_name' => 'entity_reference_1',
+            'arguments' => array(),
+          ),
+        ),
+      ),
+    );
+
+    // Get values from selection handler.
+    $handler = entity_reference_get_selection_handler($field, $instance);
+    $result = $handler->getReferencableEntities();
+
+    $success = FALSE;
+    foreach ($result as $node_type => $values) {
+      foreach ($values as $nid => $label) {
+        if (!$success = $nodes[$node_type][$nid] == trim(strip_tags($label))) {
+          // There was some error, so break.
+          break;
+        }
+      }
+    }
+
+    $this->assertTrue($success, 'Views selection handler returned expected values.');
+  }
+}
diff --git a/core/modules/views/lib/Drupal/views/Tests/ViewStorageTest.php b/core/modules/views/lib/Drupal/views/Tests/ViewStorageTest.php
index 5d31134..57a6f85 100644
--- a/core/modules/views/lib/Drupal/views/Tests/ViewStorageTest.php
+++ b/core/modules/views/lib/Drupal/views/Tests/ViewStorageTest.php
@@ -19,7 +19,7 @@
  * @see Drupal\views\Plugin\Core\Entity\View
  * @see Drupal\views\ViewStorageController
  */
-class ViewStorageTest extends ViewUnitTestBase {
+class ViewStorageTest extends ViewTestBase {
 
   /**
    * Properties that should be stored in the configuration.
@@ -54,16 +54,16 @@ class ViewStorageTest extends ViewUnitTestBase {
   protected $controller;
 
   /**
-   * Views used by this test.
+   * Modules to enable.
    *
    * @var array
    */
-  public static $testViews = array('test_view_storage');
+  public static $modules = array('node', 'search', 'comment', 'taxonomy');
 
   public static function getInfo() {
     return array(
-      'name' => 'View storage tests',
-      'description' => 'Tests the CRUD functionality for a view.',
+      'name' => 'Configuration entity CRUD tests',
+      'description' => 'Tests the CRUD functionality for View.',
       'group' => 'Views',
     );
   }
@@ -96,8 +96,8 @@ function testConfigurationEntityCRUD() {
    * Tests loading configuration entities.
    */
   protected function loadTests() {
-    $view = entity_load('view', 'test_view_storage');
-    $data = config('views.view.test_view_storage')->get();
+    $view = $this->loadView('archive');
+    $data = config('views.view.archive')->get();
 
     // Confirm that an actual view object is loaded and that it returns all of
     // expected properties.
@@ -123,8 +123,26 @@ protected function loadTests() {
       }
     }
 
+    // Fetch data for all configuration entities and default view configurations.
+    $all_configuration_entities = $this->controller->load();
+    $all_config = config_get_storage_names_with_prefix('views.view');
+
+    // Remove the 'views.view.' prefix from config names for comparision with
+    // loaded configuration entities.
+    $prefix_map = function ($value) {
+      $parts = explode('.', $value);
+      return end($parts);
+    };
+
+    // Check that the correct number of configuration entities have been loaded.
+    $count = count($all_configuration_entities);
+    $this->assertEqual($count, count($all_config), format_string('The array of all @count configuration entities is loaded.', array('@count' => $count)));
+
+    // Check that all of these machine names match.
+    $this->assertIdentical(array_keys($all_configuration_entities), array_map($prefix_map, $all_config), 'All loaded elements match.');
+
     // Make sure that loaded default views get a UUID.
-    $view = views_get_view('test_view_storage');
+    $view = views_get_view('frontpage');
     $this->assertTrue($view->storage->uuid());
   }
 
@@ -142,7 +160,7 @@ protected function createTests() {
     }
 
     // Create a new View instance with config values.
-    $values = config('views.view.test_view_storage')->get();
+    $values = config('views.view.glossary')->get();
     $created = $this->controller->create($values);
 
     $this->assertTrue($created instanceof View, 'Created object is a View.');
@@ -158,9 +176,9 @@ protected function createTests() {
     }
 
     // Check the UUID of the loaded View.
-    $created->set('name', 'test_view_storage_new');
+    $created->set('name', 'glossary_new');
     $created->save();
-    $created_loaded = entity_load('view', 'test_view_storage_new');
+    $created_loaded = $this->loadView('glossary_new');
     $this->assertIdentical($created->uuid(), $created_loaded->uuid(), 'The created UUID has been saved correctly.');
   }
 
@@ -169,7 +187,7 @@ protected function createTests() {
    */
   protected function displayTests() {
     // Check whether a display can be added and saved to a View.
-    $view = entity_load('view', 'test_view_storage_new');
+    $view = $this->loadView('frontpage');
 
     $new_id = $view->newDisplay('page', 'Test', 'test');
     $display = $view->get('display');
@@ -181,9 +199,10 @@ protected function displayTests() {
     $executable->initDisplay();
     $this->assertTrue($executable->displayHandlers[$new_id] instanceof Page, 'New page display "test" uses the right display plugin.');
 
-    $view->set('name', 'test_view_storage_new_new2');
+
+    $view->set('name', 'frontpage_new');
     $view->save();
-    $values = config('views.view.test_view_storage_new_new2')->get();
+    $values = config('views.view.frontpage_new')->get();
 
     $this->assertTrue(isset($values['display']['test']) && is_array($values['display']['test']), 'New display was saved.');
   }
@@ -193,7 +212,7 @@ protected function displayTests() {
    */
   protected function statusTests() {
     // Test a View can be enabled and disabled again (with a new view).
-    $view = entity_load('view', 'test_view_storage_new_new2');
+    $view = $this->loadView('backlinks');
 
     // The view should already be disabled.
     $view->enable();
@@ -201,7 +220,7 @@ protected function statusTests() {
 
     // Check the saved values.
     $view->save();
-    $config = config('views.view.test_view_storage_new_new2')->get();
+    $config = config('views.view.backlinks')->get();
     $this->assertFalse($config['disabled'], 'The changed disabled property was saved.');
 
     // Disable the view.
@@ -210,17 +229,28 @@ protected function statusTests() {
 
     // Check the saved values.
     $view->save();
-    $config = config('views.view.test_view_storage_new_new2')->get();
+    $config = config('views.view.backlinks')->get();
     $this->assertTrue($config['disabled'], 'The changed disabled property was saved.');
   }
 
   /**
+   * Loads a single configuration entity from the controller.
+   *
+   * @param string $view_name
+   *   The machine name of the view.
+   *
+   * @return object Drupal\views\ViewExecutable.
+   *   The loaded view object.
+   */
+  protected function loadView($view_name) {
+    $load = $this->controller->load(array($view_name));
+    return reset($load);
+  }
+
+  /**
    * Tests the display related functions like getDisplaysList().
    */
   protected function displayMethodTests() {
-    // Enable the system module so l() can work using url_alias table.
-    $this->enableModules(array('system'));
-
     $config['display'] = array(
       'page_1' => array(
         'display_options' => array('path' => 'test'),
@@ -362,7 +392,7 @@ protected function displayMethodTests() {
    * Tests the createDuplicate() View method.
    */
   public function testCreateDuplicate() {
-    $view = views_get_view('test_view_storage');
+    $view = views_get_view('archive');
     $copy = $view->storage->createDuplicate();
 
     $this->assertTrue($copy instanceof View, 'The copied object is a View.');
diff --git a/core/modules/views/lib/Drupal/views/ViewExecutable.php b/core/modules/views/lib/Drupal/views/ViewExecutable.php
index 1b6e4fc..ec1fc6d 100644
--- a/core/modules/views/lib/Drupal/views/ViewExecutable.php
+++ b/core/modules/views/lib/Drupal/views/ViewExecutable.php
@@ -1413,7 +1413,7 @@ public function preExecute($args = array()) {
     }
 
     // Allow hook_views_pre_view() to set the dom_id, then ensure it is set.
-    $this->dom_id = !empty($this->dom_id) ? $this->dom_id : hash('sha256', $this->storage->get('name') . REQUEST_TIME . mt_rand());
+    $this->dom_id = !empty($this->dom_id) ? $this->dom_id : md5($this->storage->get('name') . REQUEST_TIME . rand());
 
     // Allow the display handler to set up for execution
     $this->display_handler->preExecute();
diff --git a/core/modules/views/lib/Drupal/views/ViewsException.php b/core/modules/views/lib/Drupal/views/ViewsException.php
new file mode 100644
index 0000000..8085db2
--- /dev/null
+++ b/core/modules/views/lib/Drupal/views/ViewsException.php
@@ -0,0 +1,15 @@
+<?php
+
+/**
+ * @file
+ * Definition of Drupal\views\ViewsException.
+ */
+
+namespace Drupal\views;
+
+use Exception;
+
+/**
+ * Defines an exception thrown when Views operations fail.
+ */
+class ViewsException extends Exception { }
diff --git a/core/modules/views/tests/views_test_config/test_views/views.view.test_view_storage.yml b/core/modules/views/tests/views_test_config/test_views/views.view.test_view_storage.yml
deleted file mode 100644
index c28829f..0000000
--- a/core/modules/views/tests/views_test_config/test_views/views.view.test_view_storage.yml
+++ /dev/null
@@ -1,53 +0,0 @@
-api_version: '3.0'
-base_table: views_test_data
-core: '8'
-module: views
-description: 'Storage Test View for testing.'
-disabled: true
-display:
-  default:
-    display_options:
-      defaults:
-        fields: '0'
-        pager: '0'
-        pager_options: '0'
-        sorts: '0'
-      fields:
-        id:
-          field: id
-          id: id
-          relationship: none
-          table: views_test_data
-      sorts:
-        id:
-          field: id
-          id: id
-          order: ASC
-          relationship: none
-          table: views_test_data
-    display_plugin: default
-    display_title: Master
-    id: default
-    position: '0'
-  page_1:
-    id: page_1
-    display_title: Page
-    display_plugin: page
-    position: '1'
-    display_options:
-      query:
-        type: views_query
-        options: {  }
-      path: test_view_storage
-  block_1:
-    id: block_1
-    display_title: Block
-    display_plugin: block
-    position: '2'
-    display_options:
-      query:
-        type: views_query
-        options: {  }
-human_name: 'Storage Test View'
-name: test_view_storage
-tag: 'test'
