views:

44

answers:

2

I have a drupal module that requires other files from the web. Is it possible for the module to download these files as its being activated?

+2  A: 

Assuming PHP is configured to allow remote file access (see allow_url_fopen) and the module directory have write permissions, you can download any needed files in hook_enable or, probably even better, hook_install.

Vinicius Pinto
+3  A: 

The Drupal Way is to the use the File Interface and the install hooks:

If the file only needs to be downloaded once, it's probably better to use hook_install() and use hook_requirements() to provide feedback on whether it worked. If you need fresh data every time the module's enabled, opt for hook_enable().

In terms of downloading files, use whatever PHP method you want. If you need to use an external library, either put it within your module's directory and use include and/or require, or consider using the Libraries API, which aims to provide a central repository for third-party scripts and libraries.

Once you have the file data, you'd use the File Interface. Modules have access to the files directory of a site (defined in Site configuration -> File system). You'd first create your own directory under it using file_create_path(), then save data to it using file_save_data(). Check out the rest of the File Interface API documentation for other things you can do.

Then, once it's saved, just check to see if the data's available with file system using file_check_location() and access it with file_get_contents() or include/require.

Mark Trapp
No, as I said, you only have write access to the files folder. If you're trying to ensure library dependence, the Drupal Way is to ask the user to download the library and check for it in hook_requirements. However, what I described above will still work even in your use-case: if you can download and access the library, what does it matter where it is saved?
Mark Trapp
I suggested the Libraries API as an alternative to sticking a download library (if you needed one to get the file you wanted to download) in your module folder, as it's generally frowned upon to package external libraries in Drupal modules (and prohibited if you want to publish to drupal.org).
Mark Trapp
If you're planning on publishing it to drupal.org, don't do anything (other than implement hook_requirements). Ask the user to download the required libraries in the README: it's more important you follow convention than trying to download files without the user's consent. If this is an internal module, you should only need to download to files and include it from there for use. It's not a requirement that libraries be in `sites/all/libraries` or your module's folder in order to be able to include them for use in your module, and it has the added benefit of keeping your module folder pristine.
Mark Trapp