< BACK

Move files from multiple drupal sites to the site they belong

A long time ago I had a multisite installation. Eventually I moved all sites to their own directories but the files directory, once shared by all sites, remained as one.

Now I’m moving all sites to a new server and right now is the perfect opportunity to move files where they belong.

The problem is, how to know which file belongs to what site? If you take a look at the structure of the directory there’s just no way to tell.

But Drupal is just amazing, why? Because it keeps record of all the files needed in a table. This way we can get a list of all the files needed for that particular site and copy/move the files to the site’s directory. Yes, we can do this manually, but is no good if we’re talking about thousands of files.

Export the files needed by the site

With MySQL we just do:

D6:
SELECT filepath FROM files INTO OUTFILE ‘/tmp/files.txt’;

D7:
SELECT filepath FROM managed_files INTO OUTFILE ‘/tmp/files.txt’;

If we take a look at files.txt we’ll see we have a huge list of files, something like:

sites/default/files/talis1.jpg
sites/default/files/pic_02.jpg
sites/default/files/pic_03.jpg
sites/default/files/pic_05.jpg
sites/default/files/pic_07.jpg
sites/default/files/pic_09.jpg

Now, remember I said I was moving the sites to a new server? Well I had to move the files too and for my own sake, I recreated the structure of the files in /srv so I have something like:

/srv/www/sites/default/files/tails1.jpg

This way I save myself a few lines in the script.

The script

The script is really simple, it does three things and is written in Python.

1. Iterate over each line of the file files.txt

2. Strip the n that MySQL added on each line when we exported the file

4. Move the file to the final destination

#!/usr/bin/python
from subprocess import call
for line in open(“/tmp/files.txt”, “r”):
    file = line.strip()
    print “Moving file ” + file
    call([“mv”, “/srv/www/” + file, “/srv/www/example.com/files”])

That’s it. Save the script as whatever.py, give it permission to execute (chmod u+x) and run it. If you can’t move files around in those directories you have to run the script as sudo. You’ll need to create any directory that you doesn’t exists too.


Share this: