CYB-324 CYB-338 CYB-339

Refactor Gallery API to make it run much faster.
Now it uses pure SQL to get the data, and iterates over it in Ruby to
  make the format better for the API
CYB-338 and CYB-339 were too closely tied together to do separately.