I have a Facebook-style chat on my drupal website, however the script was lacking user picture integration. I managed to get user pictures, but if the user didn't set picture and is using a default picture I'm getting a broken image and a 404 not found
in the logs. I've tried to fetch gravatar
for users without a picture set, but couldn't make it work.
/**
* This function returns the URL of the avatar of the specified user ID.
*
* @param userid the user ID of the user
* @param image if the image includes more than just a user ID, this param is passed
* in from the avatar row in the buddylist and get user details functions.
* @return the link of the user ID's profile
*/
function get_avatar($image, $user_id, $account) {
return "http://mypage.com/files/pictures/picture-" . ($user_id) . ".jpg";
if (empty($account->picture)) {
return "http://www.gravatar.com/avfatar/" . md5($image) . "?d=identicon";
}
}
Your issue is that you return your image immediately, regardless of whether it's there:
function get_avatar($image, $user_id, $account)
{
//THE NEXT LINE RETURNS FROM THE FUNCTION REGARDLESS
return "http://mypage.com/files/pictures/picture-" . ($user_id) . ".jpg";
//THIS CODE NEVER RUNS
if (empty($account->picture)) {
return "http://www.gravatar.com/avfatar/" . md5($image) . "?d=identicon";
}
}
What you need to do is the following:
function get_avatar($image, $user_id, $account)
{
$imgurl ="http://mypage.com/files/pictures/picture-" . ($user_id) . ".jpg";
if (!is_imgurl_good($imgurl)) {
$imgurl = "http://www.gravatar.com/avfatar/" . md5($image) . "?d=identicon";
}
return $imgurl;
}
In the above, you will have to write a function, is_imgurl_good
that returns a boolean
indicating whether the image is good. true
if it is and false
if not. There are many ways to go about writing that function which is beyond the scope of this question, but you can test the approach with this:
function is_imgurl_good($imgurl) {
return false;//Check that if this returns false the previous function works
//return true; //Comment out the first line and uncomment this one to show the reverse case.
//put your actual code here to decide whether $imgurl is a valid image.
}