Steps to reproduce:

  • Add media field to some content type
  • Upload some media
  • On node edit page click "Browse media" button
  • On media library dialog select some image and click "Select media" button

The image does not get added to the form as expected. An ajax error appears in JS console.
The URL requested by ajax call is like follows:

http://examle.local/d8/docroot/d8/docroot/admin/content/media-widget?media_library_widget_id=field_media-&media_library_allowed_types%5Baudio%5D=audio&media_library_allowed_types%5Bfile%5D=file&media_library_allowed_types%5Bimage%5D=image&media_library_allowed_types%5Bremote_video%5D=remote_video&media_library_allowed_types%5Bvideo%5D=video&media_library_remaining=1&_wrapper_format=drupal_modal&ajax_form=1&_wrapper_format=drupal_ajax
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

Chi created an issue. See original summary.

Chi’s picture

Title: Media library: 404 error » Media library does not work when Drupal is installed into a sub-directory
Issue summary: View changes
cbccharlie’s picture

I have created a patch that removes the subfolder to generate the path correctly.

cbccharlie’s picture

wwedding’s picture

Status: Active » Needs review

This solved the issue for me just fine, thanks for the patch!

Manually tested on 8.6.3 in a subdirectory 1 level deep and 2 levels deep.

m.abdulqader’s picture

This patch fixed the issue when used Media Library with Seeds Distribution.

truptidiwani’s picture

Title: Media library does not work when Drupal is installed into a sub-directory » media_library_widget_id
Component: menu system » media system
Chi’s picture

Title: media_library_widget_id » Media library does not work when Drupal is installed into a sub-directory
Pancho’s picture

Note that in #2504115-28: AJAX forms should submit to $form['#action'] instead of <current>, there's another patch for this bug, which however isn't quite working for me, as the /image (or /video) part is missing. #4 works though.

Morten-H’s picture

The patch from comment #4 fixed the issue for me on drupal 8.6.10.

Any update on when this can be expected to be fixed / added to core?

Per’s picture

The patch from #4 works fine on Drupal 8.6.12 and php 7.1
Thanks

Berdir’s picture

+++ b/core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php
@@ -69,6 +69,10 @@ public function viewsForm(array &$form, FormStateInterface $form_state) {
     // not the form action. This causes bugs when this form is rendered from an
     // AJAX path like /views/ajax, which cannot process AJAX form submits.
     $url = parse_url($form['#action'], PHP_URL_PATH);
+    if (base_path() != '/') {
+      $url = preg_replace('/^' . preg_quote(base_path(), '/') . '/', '', $url);
+      $url = '/' . $url;
+    }
     $query = \Drupal::request()->query->all();
     $query[FormBuilderInterface::AJAX_FORM_REQUEST] = TRUE;

The whole part here smells like a workarounds/hack, we have lots of open issues on views and its inconsistent/broken handling of repeated ajax calls.

Pancho’s picture

The whole part here smells like a workarounds/hack

True, it’s exactly that: a hack. But then again, this is not some custom edge-case aggregated view. It’s: Media library does not work when Drupal is installed into a sub-directory. :/

I will search a bit around, though, if I can find something related in the Views queue. If you have a particular issue in mind, please share.

Berdir’s picture

What I mean is that already the existing code looks like a hack, reminds me of #2866386: Assert the view path is set correctly after second ajax request and all its related issues. So maybe if we fix that issue properly, we can remove this and it might just work?

Maybe I'm also wrong :)

seanB’s picture

Status: Needs review » Closed (duplicate)

Just found #2582295: Confirmation cancel links are incorrect if installed in a subdirectory which seems to be the cause of this issue. Closing this as a duplicate.

seanB’s picture

Status: Closed (duplicate) » Needs work

Let's reopen this. There is no good way to solve this generically, Created #3044656: Add a helper method to strip subdirectories from URL paths for situations like this, to strip subdirectories when we know the URL would contain them and we would like to add processing of the path.

seanB’s picture

seanB’s picture

Issue tags: +Media Initiative
m.abdulqader’s picture

Version: 8.6.x-dev » 8.7.x-dev

+1 for 8.7.x-dev

m.abdulqader’s picture

Patch 17 works for Drupal 8.7.1

mero.S’s picture

I am working with version 8.7.1, and not one of the solutions listed here has helped me.

Ravi Shankar Karnati’s picture

Same like #21, with Acquia lighting (8.x-4.000) and Drupal 7.1, issue not fixed with the above mentioned patches. Thanks.

deepaksingh05’s picture

Wim Leers’s picture

I agree with @Berdir in #12.

#2962525: Create a field widget for the Media library module introduced the use of Url::fromUserInput() and feeds it parse_url($form['#action'], PHP_URL_PATH). That's where things break when it's installed in subdirectories. Berdir is right that this is just a work-around for a long-existing core bug: #2504115: AJAX forms should submit to $form['#action'] instead of <current>.

On the one hand I'm tempted to close this and bump #2504115: AJAX forms should submit to $form['#action'] instead of <current> to critical. That means we don't keep adding more work-arounds.

On the other hand, I want to be pragmatic. I see two simpler solutions. Attached. (Untested)

Ravi Shankar Karnati’s picture

The above mentioned patches are not working (#23 and #24) , getting the below Ajax error.
Site info : Drupal 8.7 and PHP 7.2.

↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /admin/content/media-widget?ajax_form=1&_wrapper_format=drupal_ajax&media_library_opener_id=field%3Afield_hero_image-field_paragraph_reference-0-subform&media_library_allowed_types%5Bbanner%5D=banner&media_library_selected_type=banner&media_library_remaining=1&hash=0M1ESdYzAbAuTrU80fZjB5p4Q23gelP3EUJ8eWgJe-0↵StatusText: parsererror↵ResponseText: ↵Media | Liberty Insurance Ireland↵Skip to main content↵Toolbar items↵Back to site↵Manage↵Administration menuToolsIndexFlush all cachesFlush CSS and JavascriptFlush plugins cacheFlush render cacheFlush routing and links cacheFlush static cacheFlush twig cacheFlush views cacheRun cronRun updatesLogoutContentAdd contentBasic pageBlogCareersFAQLanding pageSafety centreSports HubWebformAdd mediaAudio fileBannerDocumentEmbed VideoIconImageVideo fileFilesPollsScheduled updatesStructureBlock layoutAdd custom blockCustom block libraryTypesBasic blockClickable BannerGoogle MapHTML BlockLocation for RepairerPoll BlockSearch Result Ad BoxSports HUB BannerContent typesAdd content typeBasic pageManage fieldsManage form displayManage displayDeleteBlogManage fieldsManage form displayManage displayDeleteCareersManage fieldsManage form displayManage displayDeleteFAQManage fieldsManage form displayManage displayDeleteLanding pageManage fieldsManage form displayManage displayDeleteSafety centreManage fieldsManage form displayManage displayDeleteSports HubManage fieldsManage form displayManage displayDeleteWebformManage fieldsManage form displayManage displayDeleteContextDisplay modesForm modesAdd new form modeView modesAdd new view modeMedia typesAudio fileManage fieldsManage form displayManage displayDeleteBannerManage fieldsManage form displayManage displayDeleteDocumentManage fieldsManage form displayManage displayDeleteEmbed VideoManage fieldsManage form displayManage displayDeleteIconManage fieldsManage form displayManage displayDeleteImageManage fieldsManage form displayManage displayDeleteVideo fileManage fieldsManage form displayManage displayDeleteMenusAdd menuAdministrationAdd linkDeleteBusiness InsuranceAdd linkDeleteCar InsuranceAdd linkDeleteCustomer InformationAdd linkDeleteFleet InsuranceAdd linkDeleteFooterAdd linkDeleteHamburger MenuAdd linkDeleteHeader MenuAdd linkDeleteLIBERTY INSURANCE & YOUAdd linkDeleteLIBERTY INSURANCE IRELANDAdd linkDeleteMain navigationAdd linkDeleteMenu : About UsAdd linkDeleteMenu ExampleAdd linkDeleteMenu: Home InsuranceAdd linkDeleteMobile Hamburger MenuAdd linkDeleteMobile MenuAdd linkDeleteMotorcycle InsuranceAdd linkDeleteSafety centre header MenuAdd linkDeleteSafety centre menuAdd linkDeleteSports HUB Header MenuAdd linkDeleteToolsAdd linkDeleteUSEFUL LINKSAdd linkDeleteUser account menuAdd linkDeleteVan InsuranceAdd linkDeleteWeather Safety Center MenuAdd linkDeleteYOUR COVERAdd linkDeleteNotification ListAdd NotificationParagraph types2 Column CTA with iconsManage fieldsManage form displayManage displayDelete2 Column Media with TextManage fieldsManage form displayManage displayDelete3 Column CTA with iconsManage fieldsManage form displayManage displayDelete3 Column Media with TextManage fieldsManage form displayManage displayDelete4 Column Contact Card Without Background ColorManage fieldsManage form displayManage displayDelete4 Column images with text & CTAsManage fieldsManage form displayManage displayDeleteAnswersManage fieldsManage form displayManage displayDeleteBenefits Comparison tableManage fieldsManage form displayManage displayDeleteBlock ParagraphManage fieldsManage form displayManage displayDeleteCTA - Large Rectangle - Bottom pageManage fieldsManage form displayManage displayDeleteCTA GroupingManage fieldsManage form displayManage displayDeleteCTA Large Double image CTAManage fieldsManage form displayManage displayDeleteCTA Large RectangleManage fieldsManage form displayManage displayDeleteCTAManage fieldsManage form displayManage displayDeleteCTA with Help Text & Drop DownManage fieldsManage form displayManage displayDeleteCTA with LHS TextManage fieldsManage form displayManage displayDeleteCTA with LHS imageManage fieldsManage form displayManage displayDeleteCTA with Large Text & TitleManage fieldsManage form displayManage displayDeleteCTA with Title and TextManage fieldsManage form displayManage displayDeleteCTA x 2 Column Large RectangleManage fieldsManage form displayManage displayDeleteCTAs x 2 with LHS imageManage fieldsManage form displayManage displayDeleteCard BlockManage fieldsManage form displayManage displayDeleteContact UsManage fieldsManage form displayManage displayDeleteDocument list with iconManage fieldsManage form displayManage displayDeleteDocumentsManage fieldsManage form displayManage displayDeleteFeatures module blockManage fieldsManage form displayManage displayDeleteHTML TextManage fieldsManage form displayManage displayDeleteHelp text drop down linksManage fieldsManage form displayManage displayDeleteHero Banner – 3 CTAsManage fieldsManage form displayManage displayDeleteHero Banner – Countdown TimerManage fieldsManage form displayManage displayDeleteHero Banner – Image with CTA & IconManage fieldsManage form displayManage displayDeleteHero Banner – Simple ImageManage fieldsManage form displayManage displayDeleteHero Banner – SliderManage fieldsManage form displayManage displayDeleteHero Banner – Video Manage fieldsManage form displayManage displayDeleteHero Banner – Video small embeddedManage fieldsManage form displayManage displayDeleteIcon SliderManage fieldsManage form displayManage displayDeleteIcon with CTA Manage fieldsManage form displayManage displayDeleteIconsManage fieldsManage form displayManage displayDeleteImage with OptionsManage fieldsManage form displayManage displayDeleteLarge Title TextManage fieldsManage form displayManage displayDeleteOffices in IrelandManage fieldsManage form displayManage displayDeleteOverlay BlockManage fieldsManage form displayManage displayDeletePolicy LinksManage fieldsManage form displayManage displayDeletePolicy benefitsManage fieldsManage form displayManage displayDeletePolicy featuresManage fieldsManage form displayManage displayDeleteQuick Links - 3 column blockManage fieldsManage form displayManage displayDeleteQuick Links claimsManage fieldsManage form displayManage displayDeleteQuick LinksManage fieldsManage form displayManage displayDeleteSignpost containerManage fieldsManage form displayManage displayDeleteSignpostingManage fieldsManage form displayManage displayDeleteSlideManage fieldsManage form displayManage displayDeleteSlider text with RHS imageManage fieldsManage form displayManage displayDeleteSmall TextManage fieldsManage form displayManage displayDeleteTeam LayoutManage fieldsManage form displayManage displayDeleteTestimonialManage fieldsManage form displayManage displayDeleteText with Emergency Number CTAManage fieldsManage form displayManage displayDeleteTrustpilot APIManage fieldsManage form displayManage displayDeleteWith Background Color Contact CardManage fieldsManage form displayManage displayDeleteWith Background Image Contact CardManage fieldsManage form displayManage displayDeleteTaxonomyAdd vocabularyBlog CategoryEditManage fieldsManage form displayManage displayDeleteBlog freeform tagsEditManage fieldsManage form displayManage displayDeleteContent TagsEditManage fieldsManage form displayManage displayDeleteFAQ CategoriesEditManage fieldsManage form displayManage displayDeleteFAQ TagsEditManage fieldsManage form displayManage displayDeleteFeatures and benefitsEditManage fieldsManage form displayManage displayDeleteMedia TagsEditManage fieldsManage form displayManage displayDeleteSearch CategoryEditManage fieldsManage form displayManage displayDeleteSports HUB CategoryEditManage fieldsManage form displayManage displayDeleteViewsAdd new viewWebformsConditional fieldsEntity Log list of entitiesQuick TabsAppearanceInstall new themeSettingsUpdateExtendInstall new moduleUninstall moduleUpdateConfigurationPeopleAccount settingsManage displayManage fieldsManage form displayAutomated logout settingsCAPTCHA module settingsCAPTCHA examplesreCAPTCHALogin SecurityRestrict IPSession limitSimple OAuthIP address bansModeration DashboardSystemAcquia Connector settingsBasic site settingsEU Cookie ComplianceMail SystemField QuizGoogle Tag ManagerLightningAPILayoutMediaRolesSchedulerMemcacheSecurity ReviewSwift MailerMessage settingsTest e-mail settingsTransport settingsCronEntity Log ConfigurationGeneral Settings FormSecurity Kit settingsContent authoringDiffEntity Usage SettingsEntity browsersHoneypot configurationOverride Node OptionsParagraphs settingsPoll settingsQuick Node Clone SettingsText formats and editorsTop Question OrderingText editor embed buttonsAccess unpublishedContent LockUser interfaceEasy BreadcrumbShortcutsResponsive previewDevelopmentPerformanceAdvAggLogging and errorsMaintenance modeConfiguration synchronizationImportExportPHPExcel cache settingsMediaCrop typesFile systemImage stylesImageWidgetCrop settingsMedia settingsResponsive image stylesImage toolkitSearch and metadataURL aliasesMetatagSettingsSearch API AttachmentsSearch APISimple XML SitemapSitemapURL redirectsAdd redirectImportSettingsFacetsRegional and languageRegional settingsDate and time formatsSecurityPassword PolicyWeb servicesAcquia LiftConsumersJSON:APIOAuthOpenAPI DownloadsRSS publishingSocial FeedFacebook Settings FormInstagram Settings FormTwitter Settings FormStyled Google Map settings pageAcquia Content HubSocial media settingsWorkflowWorkflow participant settingsWorkflowsScheduled Updates OverviewScheduled Update TypesRun Scheduled UpdatesScheduled Updates SettingsEmail TemplatesPeopleAdd a new userPermissionsRolesAdd a new roleAdministratorDeleteEdit permissionsAnonymous userDeleteEdit permissionsApproverDeleteEdit permissionsAuthenticated userDeleteEdit permissionsBasic page creatorDeleteEdit permissionsBasic page reviewerDeleteEdit permissionsBlog creatorDeleteEdit permissionsBlog reviewerDeleteEdit permissionsCareers creatorDeleteEdit permissionsCareers reviewerDeleteEdit permissionsDigital Content EditorDeleteEdit permissionsEditorDemoDeleteEdit permissionsFAQ creatorDeleteEdit permissionsFAQ reviewerDeleteEdit permissionsHR Content EditorDeleteEdit permissionsLanding page creatorDeleteEdit permissionsLanding page reviewerDeleteEdit permissionsLayout managerDeleteEdit permissionsMarketing Content EditorDeleteEdit permissionsMedia creatorDeleteEdit permissionsMedia managerDeleteEdit permissionsPublisherDeleteEdit permissionsReviewerDeleteEdit permissionsReviewer2DeleteEdit permissionsSafety centre creatorDeleteEdit permissionsSafety centre reviewerDeleteEdit permissionsSports Hub creatorDeleteEdit permissionsSports Hub reviewerDeleteEdit permissionsWebform creatorDeleteEdit permissionsWebform reviewerDeleteEdit permissionsReportsAvailable updatesEvents Log TrackField listUsed in viewsMemcache statisticsSecurity reviewStatus reportViews pluginsWebform pluginsHelp ↵Shortcuts↵User-defined shortcutsExtendFAQ Top Question OrderingVideo file settings for Video fileEdit shortcuts ↵Edit↵dev_admin↵User account actionsView profileEdit profileLog outModeration Dashboard ↵Subscription active (expires 2021/7/1)↵Media↵Add to Default shortcuts↵Breadcrumb↵Administration↵Content↵Media↵Name↵Media Tags↵- Any -AccidentAsset Tag-Demo1assetsAudioAudio Medi TagBlog MediaBusinesscar insuranceCar insurance video metatagCar Insurance- Contact Card Four ColumnCar Policy features and benefits MetaDataCar Policy features and benefits MetaData Audio1Car Policy features and benefits MetaData Doc1Car Policy features and benefits MetaData Img 1Car Policy features and benefits MetaData Video1Car Policy features and benefits MetaData Youtube Video1ClaimCommunicationDocumentHomeHome InsuranceInsuranceLiberty Safety CentreMedia tag 16Media tag8Media-Image-Tag-DemoMotor asset tagMotor insurance Audio TagMotor insurance Doc TagMotor Insurance Image TagMotor insurance video tagMotor Insurance Youtube TagMotorcyclePolicy holder1QuoteRenewal policysign postingsite notificationsSports HUB Match StatSports HUB VideoVanVan InsuranceVan Insurance Media TagVechicleVehicle Service Plan Media TagVideoWeather↵Published↵- Any -PublishedUnpublished↵Media type↵- Any -Audio fileBannerDocumentEmbed VideoIconImageVideo file↵Image alt↵Image title↵Sort by↵Newest firstName (A-Z)Name (Z-A)↵liberty-in-the-community-833.jpgMedia tags: assets↵Select liberty-in-the-community-833.jpg↵personal-insurance-536.jpgMedia tags: Business↵Select personal-insurance-536.jpg↵personal-insurance-536.jpgMedia tags: Business↵Select personal-insurance-536.jpg↵Paragraph reference document Media tags: site notifications↵Select Paragraph reference document ↵NV Test banner [please, do not use] Media tags: Motor Insurance Image Tag↵Select NV Test banner [please, do not use] ↵home-emergency-assistance2.pngMedia tags: Home Insurance↵Select home-emergency-assistance2.png↵home-emergency-assistance2.pngMedia tags: Home Insurance↵Select home-emergency-assistance2.png↵Home Insurance - Emergency Home RepairMedia tags: Video↵Select Home Insurance - Emergency Home Repair↵home-1.jpgMedia tags: Home Insurance↵Select home-1.jpg↵feature-camogie-made-us-2018-champions-1096.jpgMedia tags: Blog Media↵Select feature-camogie-made-us-2018-champions-1096.jpg↵ManagePolicy-Homeinsurance.pngMedia tags: Home Insurance↵Select ManagePolicy-Homeinsurance.png↵Rider Skills Approved AssessorsMedia tags: Document↵Select Rider Skills Approved Assessors↵Trustpilot_Extra_Large_NewMedia tags: assets↵Select Trustpilot_Extra_Large_New↵Trustpilot_Large_NewMedia tags: assets↵Select Trustpilot_Large_New↵Trustpilot_Medium_NewMedia tags: assets↵Select Trustpilot_Medium_New↵Trustpilot_Small_NewMedia tags: assets↵Select Trustpilot_Small_New↵Trustpilot_Extra_Small_NewMedia tags: assets↵Select Trustpilot_Extra_Small_New↵Trustpilot_Extra_LargeMedia tags: assets↵Select Trustpilot_Extra_Large↵Sport Made Me Ready for the Real World - Cora StauntonMedia tags: ↵Select Sport Made Me Ready for the Real World - Cora Staunton↵feature-get-a-car-insurance-quote-the-easy-way-712.jpgMedia tags: Blog Media↵Select feature-get-a-car-insurance-quote-the-easy-way-712.jpg↵Pagination↵Current page↵1↵Page↵2↵Page↵3↵Page↵4↵Page↵5↵Page↵6↵Page↵7↵Page↵8↵Page↵9↵Page↵10↵…↵Next page↵››↵Last page↵Last »↵{"ajaxPageState":{"theme":"seven","theme_token":"icVSpdTWol47D-zJab49GI-872warDsfozsrSJopMOk","libraries":"acquia_connector\/acquia_connector.icons,admin_toolbar\/toolbar.tree,admin_toolbar_tools\/toolbar.icon,autologout\/drupal.autologout,ckeditor\/drupal.ckeditor,classy\/base,classy\/file,classy\/messages,contextual\/drupal.contextual-links,contextual\/drupal.contextual-toolbar,core\/drupal.active-link,core\/drupal.autocomplete,core\/drupal.collapse,core\/drupal.date,core\/drupal.states,core\/drupal.tabledrag,core\/drupal.tableresponsive,core\/drupal.vertical-tabs,core\/html5shiv,core\/normalize,embed\/embed,field_group\/core,field_group\/formatter.tabs,file\/drupal.file,filter\/drupal.filter,liberty_cms_general\/extra.admin,liberty_cms_general\/liberty_seven_ui,liberty_cms_general\/page_not_found,lightning_scheduler\/widget,media_library\/ui,media_library\/widget,menu_ui\/drupal.menu_ui,node\/drupal.node,paragraphs\/drupal.paragraphs.actions,paragraphs\/drupal.paragraphs.widget,path\/drupal.path,pathauto\/widget,poll\/drupal.poll-links,responsive_preview\/drupal.responsive-preview,seven\/global-styling,seven\/node-form,shortcut\/drupal.shortcut,site_notification_entity\/notification-alert,token\/token,toolbar\/toolbar,toolbar\/toolbar.escapeAdmin,user\/drupal.user.icons,views\/views.ajax,views\/views.module"},"autologout":{"timeout":900000,"timeout_padding":20000,"message":"Your session is about to expire. Do you want to reset it?","redirect_url":{},"title":"Liberty Insurance Ireland Alert","refresh_only":true,"no_dialog":false,"use_alt_logout_method":false},"views":{"ajax_path":"\/views\/ajax?ajax_form=1\u0026_wrapper_format=html\u0026media_library_opener_id=field%3Afield_hero_image-field_paragraph_reference-0-subform\u0026media_library_allowed_types%5Bbanner%5D=banner\u0026media_library_selected_type=banner\u0026media_library_remaining=1\u0026hash=0M1ESdYzAbAuTrU80fZjB5p4Q23gelP3EUJ8eWgJe-0","ajaxViews":{"views_dom_id:dd3d7b31289d6cb6774c8c563977f4b790f351f76fbfe1a92c97e464ac867505":{"view_name":"media_library","view_display_id":"widget","view_args":"","view_path":"\/admin\/content\/media-widget","view_base_path":"admin\/content\/media-widget","view_dom_id":"dd3d7b31289d6cb6774c8c563977f4b790f351f76fbfe1a92c97e464ac867505","pager_element":0}}},"ajaxTrustedUrl":{"\/admin\/content\/media-widget?ajax_form=1\u0026_wrapper_format=html\u0026media_library_opener_id=field%3Afield_hero_image-field_paragraph_reference-0-subform\u0026media_library_allowed_types%5Bbanner%5D=banner\u0026media_library_selected_type=banner\u0026media_library_remaining=1\u0026hash=0M1ESdYzAbAuTrU80fZjB5p4Q23gelP3EUJ8eWgJe-0":true,"\/admin\/content\/media-widget":true},"ajax":{"edit-submit--A3AWSkKDddI":{"url":"\/admin\/content\/media-widget?ajax_form=1\u0026_wrapper_format=html\u0026media_library_opener_id=field%3Afield_hero_image-field_paragraph_reference-0-subform\u0026media_library_allowed_types%5Bbanner%5D=banner\u0026media_library_selected_type=banner\u0026media_library_remaining=1\u0026hash=0M1ESdYzAbAuTrU80fZjB5p4Q23gelP3EUJ8eWgJe-0","callback":["Drupal\\media_library\\Plugin\\views\\field\\MediaLibrarySelectForm","updateWidget"],"event":"mousedown","keypress":true,"prevent":"click","dialogType":"ajax","submit":{"_triggering_element_name":"op","_triggering_element_value":"Insert selected"}}},"toolbar":{"breakpoints":{"toolbar.narrow":"only screen and (min-width: 16.5em)","toolbar.standard":"only screen and (min-width: 38.125em)","toolbar.wide":"only screen and (min-width: 61em)"},"subtreesHash":"S_x3O0iaV-756wPe4SVqr0PLY3YKwD6rUYhJXr13CpU"},"path":{"baseUrl":"\/","pathPrefix":"","currentPath":"admin\/content\/media-widget","currentPathIsAdmin":true,"isFront":false,"currentLanguage":"en","currentQuery":{"_wrapper_format":"html","ajax_form":"1","hash":"0M1ESdYzAbAuTrU80fZjB5p4Q23gelP3EUJ8eWgJe-0","media_library_allowed_types":{"banner":"banner"},"media_library_opener_id":"field:field_hero_image-field_paragraph_reference-0-subform","media_library_remaining":"1","media_library_selected_type":"banner"}},"pluralDelimiter":"\u0003","user":{"uid":"6","permissionsHash":"e70e446a2098d136437b70c249acbf2e2e4c37670bc60d622f6cd34b6392442c"}}↵

bendev’s picture

Status: Needs review » Needs work

same issue. Patches are not working

wwedding’s picture

Status: Needs work » Needs review

I think we need more info from #26 and #25.

I am finding that patches from #24 work fine for me, using a relatively fresh Standard Profile install of 8.7.2 with PHP 7.2.1.

The patch in #23 is a re-roll of #4 and is more or less identical (and works for me, too).

I followed the steps in the original report at a node located at: http://localhost/d87-test/web/node/3/edit

I was unable to use the media gallery to add files before either patch and was able to add files after the patch.

bendev’s picture

We have this issue on 3 of our websites where media library is installed, after the core was updated to D8.7.2

what more info would you need?

wwedding’s picture

The AJAX issue originally reported is an Error 404 during the AJAX attempt because of an incorrectly constructed path. #25 is (I think? Formatting makes it difficult) reporting a 200 response, so they're likely encountering a different issue. This might also be the case for you, as well.

What is the AJAX error, what path does it request before the patch and what does it request after? Is your website's public path a sub directory (example: http://www.example.com/subdirectory)? Did these patches work for you prior to D8.7.2?

nuez’s picture

Both patches in #24 seem to work fine.

The 'real fix' would be provided by #2504115-28: AJAX forms should submit to $form['#action'] instead of , but that might take a while before that lands. I'm in favour of one of the patches suggested in #24

On my localhost the tests in Drupal\Tests\media_library\FunctionalJavascript\MediaLibraryTest fail, as expected.

The question is: why does the testbot not fail. Looking at the test artifacts (command_output), the testbot seems to run with a URL with a subdirectory:

cd /var/www/html && sudo MINK_DRIVER_ARGS_WEBDRIVER='["chrome", {"browserName":"chrome","chromeOptions":{"args":["--disable-gpu","--headless"]}}, "http://chromedriver-jenkins-drupal-patches-99366:9515"]' -u www-data php /var/www/html/core/scripts/run-tests.sh --color --keep-results --types "PHPUnit-FunctionalJavascript" --concurrency "15" --repeat "1" --sqlite "/var/lib/drupalci/workdir/run_tests.javascript/simpletest.sqlite" --dburl "mysql://drupaltestbot:drupaltestbotpw@172.18.0.4/jenkins_drupal_patches_99366" --url "http://php-apache-jenkins-drupal-patches-99366/subdirectory" --all

With the patch I'm trying to see what kind of request url the test bot is using, and if the url actually has a subdirectory or if there is some magic happening that we don't know about:

The test should fail with the following message:

Failed asserting that two strings are equal.
Expected :'foo'
Actual   :'/whatever-subdir-if-any/admin/content/media-widget/type_three'

Status: Needs review » Needs work

The last submitted patch, 30: 2990664-30.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

nuez’s picture

The test result confirms that there is a subdirectory.

1) Drupal\Tests\media_library\FunctionalJavascript\MediaLibraryTest::testWidgetUpload
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'foo'
+'/subdirectory/admin/content/media-widget/type_three'

So the tests should fail as they do on my localhost...

nuez’s picture

nuez’s picture

After doing some more research, I think there are deeper issues with the Url::fromUserInput method.

If the user input is /subdirectory/admin/content/media-widget/type_three, then ::fromUserInput fails to strip away the '/subdirectory' before passing it on to ::fromUri, with internal: prepended.

It's literally passing: internal:/subdirectory/admin/content/media-widget/type_three to the ::fromUri method, which is incorrect: The uri should not include the subdirectory the drupal installation lives in.

The attached patched solves this issue, and possibly many others.

I'm not sure though if we always have access to $_SERVER['DOCUMENT_URI']

Pancho’s picture

In that case, this one should be related, too.

bendev’s picture

Indeed problem seems to be different

We didn't have any issue prior to D8.7.2

HTTP Result Code: 200
Debugging information follows.
Path: /admin/content/media-widget?ajax_form=1&_wrapper_format=drupal_ajax&media_library_opener_id=field%3Afield_event_img&media_library_allowed_types%5Bimage%5D=image&media_library_selected_type=image&media_library_remaining=1&hash=f0v...

Should we open a new ticket ? I don't find any other issue with 200...
thanks

nuez’s picture

As a result of the discussion with @seanB, @phenaproxima and @alexpott

  1. Option A: instead of using the value from #action we use the router. This way we can avoid several blocker issues, while getting a clean solution for this particular Media related issue.
  2. Option B: This is basically an improvement of patch #24A, but instead of continue to use ::fromUserInput we use ::fromUri, since the value we need is not really coming from user input in the first place.

There are still issues, that will need to be created/found, which might become unrelated to this particular issue if we choose option A:

  1. Documentation issue for Url::fromUserInput, which should never receive any subdirectory otherwise it will break.
  2. The fact that the testbot doesn't break with subdirectories being passed to ::fromUserInput, when it should.
nuez’s picture

Issue tags: +Needs manual testing

Adding 'Needs manual testing' as the test bot is currently not picking up the errors when there is a subdirectory.

seanB’s picture

Status: Needs work » Needs review

I think option A makes the most sense and is the more robust solution. So I think we should definitely go for that.
The code looks good to me. I would love to see some other people confirming 2990664-36-a.patch solves the issue before this is RTBC.

Pancho’s picture

From manual testing, I can confirm that, hardly surprising, 2990664-36-a.patch does solve (or work around) the issue with media library in sub-directory installs. Next successful tester may IMO promote to RTBC.

phenaproxima’s picture

@alexpott referred us to #2673980-99: RSS view with fields give wrong URL from path field, which explains why subdirectories "work" on testbot, but break locally.

That comment confirms that this issue is not automatically testable, since the testing environment itself elides this bug. So +1 for manual testing. We'll want to test on all three scenarios mentioned in the comment to be sure this works. But once we do that, I think we can mark this RTBC.

Pancho’s picture

In patch #36a, we're just completely bypassing that problem.

So while #2673980-99: RSS view with fields give wrong URL from path field may explain why the testbot doesn't fail with ::fromUserInput, it should be irrelevant to what we're doing in patch #36a.

IMO, the real question is whether we are rightfully bypassing that bug here or whether we should postpone and fix the underlying bug/s.

phenaproxima’s picture

Issue tags: +DevDaysCluj

IMO, the real question is whether we are rightfully bypassing that bug here or whether we should postpone and fix the underlying bug/s.

We discussed this with @alexpott and the consensus is that we should bypass the bug in Media Library, because fixing this For Realz is probably going to take some time and significant effort.

seanB’s picture

Just tested the following manually:
- Head works without subdirectories
- Head is broken when using subdirectory '/foo'
- Head is broken when using subdirectory '/foo/bar'
- With 2990664-36-a.patch everything works without subdirectories
- With 2990664-36-a.patch everything works using subdirectory '/foo'
- With 2990664-36-a.patch everything works using subdirectory '/foo/bar'

I think we are done here.

nuez’s picture

I've also tested this with three scenarios:

  1. no subdirectory - Doesnt fail with and without the patch
  2. subdirectory 'foo' - fails without patch, doesn't fail with patch
  3. subdirectory 'foo/bar' - fails without patch, doesn't fail with patch

I don't think this issue in https://www.drupal.org/comment/13056393#comment-13056393 is a 100% related:

It mentions testing with a url with a double slash at the beginning. I've seen this issue and I think we can reproduce that, but that's not what's happening here, we don't have the double slash. I think the double slash should throw an exception as three slashes does, and also not having any slash at the beginning. But it doesn't: in fact it strips away part of the Url. But that should be another issue.

It also says:

If Drupal is running in a single-level sub-directory (example.com/dir1), then dir1/node/1 becomes example.com/dir1/node/1 and the bug "miraculously" doesn't occur.

If the testbot actually doesn't strip away the subdirectory, but does run in a subdirectory, so the different functional tests should have failed a long time ago. So I agree that the bug miraculously doesn't occur on the testbot, but it still doesn't bring us any closer to understanding why.

seanB’s picture

Status: Needs review » Reviewed & tested by the community

I think the workaround for the media module (2990664-36-a.patch) is RTBC. The other issue might not explain why the tests didn't fail, but I don't think we should block this issue on that.

The last submitted patch, 30: 2990664-30.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

alexpott’s picture

Status: Reviewed & tested by the community » Fixed

Crediting @Chi for creating the issue.
Crediting @Pancho, @wwedding for issue review and testing.
Crediting @Berdir and @phenaproxima for issue review and management.

I think the solution here is fine. ::fromUserInput() is not meant for things that are NOT user input so the solution here is fine. We've also created issues to improve documentation and potentially work towards solutions for user input in a sub-directory.

  • alexpott committed 8b80368 on 8.8.x
    Issue #2990664 by nuez, seanB, cbccharlie, Wim Leers, deepaksingh05,...

  • alexpott committed 25a72bb on 8.7.x
    Issue #2990664 by nuez, seanB, cbccharlie, Wim Leers, deepaksingh05,...
bendev’s picture

Thanks
After testing I confirm option a also solves our issue described in #36

rosinegrean’s picture

Issue tags: -DevDaysCluj +DevDaysTransylvania

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

Frosty29’s picture

I am having this issue (actually arrived here from what was marked as duplicate https://www.drupal.org/project/drupal/issues/3020823) after recent updates. I cannot successfully select any media items. I looked at the patches mentioned above and they no longer apply as this part of the code has apparently been rewritten in 8.7.4 released 4th July. Should I open a new issue?

seanB’s picture

It would be great if you could open a new issue and provide as much information as possible. Maybe any errors in the logs, or any javascript errors. Could you also check if you can reproduce the same issue in a clean install (to make sure there is not any custom code or contrib modules breaking the functionality)?

Frosty29’s picture

seanB - my issue is not due to install being in subdirectory - as I said, I first came to his issue from another which exactly described my symptoms. I have just reverted the media_library (only) to 8.7.3 version within my 8.7.5 install and applied nuez's patch a of #37 - has no effect. I have reverted the media_library to 8.7.1 and now have the same condition as a couple of months back - when I click "Add media" I can switch to Table view and successfully select and insert media to my target. If I select using the big ticks in Grid view, nothing happens. I always used to select by big ticks... and I did not notice at the time, but suspect it stopped working when I upgraded the site from 8.6.x to 8.7.x. To be clear, the current situation in 8.7.5 is that both the Grid and Table views allow tick selections to be made, but after click "insert selected", on returning to my content type nothing has been inserted. I will try to set up a clean install, both 8.6.x and 8.7.x, and reconfirm.

Frosty29’s picture

SeanB Okay i have a local clean install (as it happens in a subdirectory, so I needed to apply patch a!) and media select worked on version 8.6.4 and was failing by 8.6.10.
Error 404 "No route found for /admin/content/media-widget"

However I am on 8.7.5 now, so clean installed that as well ... and find even with my subdirectory install of drupal, all works as expected.
This local test system is php 7.1. My server is php 7.2. But I have dozens of other modules installed on server as well...

However I do appear to be able to select in Table view again now on sever - not being aware of changing any code!
In Grid view when I tick one or more selection boxes on the media items I always see "0 items selected" and nothing can be returned.
In Table view when I tick items the counter increments properly and I am able to select and return them.
There are no console or other errors that I can see but presumably something is interfering with the javascript on grid view in my live server.
Don't know what to try now in order to diagnose the grid view issue which is preferable to use.

kle’s picture

Fresh Install of 8.7.8 (no subdirectory)
Adding Images per grid works fine. Adding Images from table fails.
Test with PHP 7.1.12 and 7.2.1
Console Error:

...
response: 200
Im Folgenden finden Sie Debugging-Informationen.
Pfad: http://roche.fr/media-library?media_library_opener_id=media_library.opener.field_widget&media_library_allowed_types%5Bimage%5D=image&media_library_selected_type=image&media_library_remaining=1&media_library_opener_parameters%5Bfield_widget_id%5D=field_bild%3A-field_para_content-0-subform&media_library_opener_parameters%5Bentity_type_id%5D=paragraph&media_library_opener_parameters%5Bbundle%5D=dummy&media_library_opener_parameters%5Bfield_name%5D=field_bild&media_library_opener_parameters%5Bentity_id%5D=2&hash=RLVx0RNu0-vN5N9WFpWcTlXS1HYtLaIznGcnJGS9CAY&_wrapper_format=drupal_ajax&ajax_form=1
Statustext: OK
Antworttext: 
{some stripped Text and Links from my Website ... }
error ajax.js:500
complete ajax.js: 239