$sql = "select u.Id, u.username, u.email, (NOW()-u.authenticationTime) as authenticateTimeDifference, u.IP, 
          f.providerId, f.requestId, f.status, u.port 
       from friends f
       left join users u on 
          u.Id = if ( f.providerId = ".$userId.", f.requestId, f.providerId ) 
       where (f.providerId = ".$userId." and f.status=".USER_APPROVED.")  or 
           f.requestId = ".$userId." ORDER BY u.username ASC";

I don´t understand the if meaning here , being used with where

// providerId and requestId is Id of  a friend pair,
   // providerId is the Id of making first friend request
   // requestId is the Id of the friend approved the friend request made by providerId

   // fetching friends, 
   // left join expression is a bit different, 
   //  it is required to fetch the friend, not the users itself

Its similat to ternary statements you'll see in other languages.
If the statement is true use the first value, if its false use the second.
So, in the example of the first IF above if f.providerId = $userId then f.requestId is supplied to the ON statement, otherwise f.providerId is used.