UPDATE: The challenge has been solved!
Would you like a free muffin? Here is how you can get one:
If you are the first person to solve our challenge, we will have a muffin delivered to you from your nearest coffee shop. Of course, we prefer that you live in a place that is reasonably accessible to coffee shops.
You don't have to be a programmer to solve this. If you have a working knowledge of English, you should be able to spot the line. But we will briefly dive into the problem for those who might like to know more.
Redirect File
If you want to redirect a path in Drupal, it is as easy as adding an entry at admin/config/search/redirect/add.
But someone might ask, "how do you redirect a file in Drupal?" Well, it depends. If you have removed or renamed a file in the files directory, you can add a redirect from the old file path to the new. That would work because the old file would no longer exist. If the file was not removed or renamed, however, the redirect will not work. There is a way around that, though. That is where the module redirect_file comes in. Here is the problem statement from the module's README file:
{% highlight text %}
- Create a redirect from /sites/default/files/test.pdf to http://google.com
- If the file exists, the redirect will not work.
- If the file does not exist, the redirect will work. {% endhighlight %}
We ran into a project that had a Drupal instance with a legacy directory at the root
of the site. The old URL path was shared through email so the hierarchy was kept in place for historical reasons. As the files in that directory become outdated, the content administrator wanted to create a redirect to an updated version of the file uploaded in the files directory.
We discovered that the redirect_file module had to be modified to work for the scenario described above. Look at the code snippet below and see if you can identify the reason why it wouldn't work for our case out-of-the-box.
{% highlight php startinline %} function redirect_file_submit($form, &$form_state) {
if (!$form_state['values']['move_existing_file']) { return FALSE; }
$source = $form_state['values']['source']; $public_file_path = variable_get('file_public_path', 'sites/default/files');
// Only move source file if it is in the 'public://' file directory. if (strstr($source, $public_file_path) !== FALSE) { $file_default_scheme = file_default_scheme() . "://"; $source_path = str_replace($public_file_path . '/', $file_default_scheme, $source); $file = redirect_file_load_file_by_url($source_path);
if ($file) {
// Rename the managed file.
file_move($file, $file->uri);
}
else if (file_exists($source_path)) {
// Rename the unmanaged file.
file_unmanaged_move($source_path, $source_path);
}
} } {% endhighlight %}
Hint: Pay attention to the inline comments.
Tweet your answer at @blencorp.
Your muffin will be waiting!