There is a theme hack or a worm circulating online which adds this code to all functions.php files. It happened to me on my local server.
Here's the code - http://pastebin.com/AUsHUng1
How do I find the theme hack that creates it? Or the worm?
UPDATE:
I have found that this line:
$elem == substr(__FILE__,-13)){
checks for the functions.php file (as it's the only one having 13 letters and using file) and by using the fputs() functions writes itself on all functions.php files.
I have deleted all the instances of the code, and, hopefully, it will not replicate itself on another theme activation. I have a local server with about 60 themes.
I still haven't found the original theme that carried the code.
UPDATE AND SOLUTION:
Clean all the malicious code (see my PasteBin link above) from all functions.php files (best to check globally using a text editor like Notepad++) and you're done. Check all downloaded themes for the code in functions.php file. There are more themes infected with this code online.