Restricting items displayed in Drupal Media library using hook_query_alter

I've been using the Drupal Media module on sites for quite a long time now but one thing that's always annoyed me slightly is that it just shows one giant list of media from every user. For small sites this often just a minor inconvenience but my current project (an intranet with many editor users) wasn't such a simple case. I had a look around and couldn't find a solution already out there and in the end came up with this little snippet using hook_query_alter():

It's not the most elegant solution ever, but it seems to do the trick. Unfortunately the Media module doesn't tag the query so I had to put in some bodgetastic tests to isolate the correct query. The nicer way to do it would be to use $query->hasTag('something')

You could easily create other conditions in here as well, such as filtering the query based on the timestamp field in the file_managed table, or you could feasibly join in other tables to do something like only displaying files uploaded from a certain field.

I should mention, this is a slight hack in the sense that it only applies to the media-7.x-1.x releases. media-7.x-2.x will use a View for the library browser so you should be able to do this kind of filtering in a much more sane way in future! However at the time of writing, the tag media-7.x-2.0-unstable6 precludes me using it on client sites…

The above code is available in a sandbox for anyone that just wants to download and use it (andymantell's sandbox: Media Library User Restrict). This will never be promoted to a full project however since the forthcoming media-7.x-2.x series should solve the problem more elegantly as mentioned above.