Facebook were able to carry out the experiment because all users have to tick
  a box agreeing to their terms and conditions. These include "internal
  operations, including troubleshooting, data analysis, testing, research and
  service improvement."
In the study, the authors point out that they stayed within the remit of the
  agreement by using a machine to pick out positive and negative posts,
  meaning no user data containing personal information was actually viewed by
  human researchers.
The study, carried out over a week in January 2012, was carried out for
  scientific purposes. But evidence that social media can have such a strong
  impact on people's mental state will certainly be of interest to advertisers.
The lead scientist, Adam Kramer, said in
  an interview when he joined Facebook in March 2012 that he took the
  job because "Facebook data constitutes the largest field study in the
  history of the world."