Created
November 22, 2014 08:09
-
-
Save dljoseph/3e604b54be8526550a86 to your computer and use it in GitHub Desktop.
SilverStripe 3.1.x - Fetch Gravatar image before writing Member record
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function onBeforeWrite(){ | |
if(!$this->ID or !$this->ImageID) { | |
$gravatarEmailHash = md5(strtolower($this->Email)); | |
$gravatarURL = "http://www.gravatar.com/avatar/$gravatarEmailHash?d=404"; | |
$headers = get_headers($gravatarURL); | |
if (strpos($headers[0],'200')) { | |
//get the extension of the gravatar image - it will be either jpeg or png - we will need it later | |
$ext = (strpos($headers[5], 'image/jpeg') === false) ? 'png' : 'jpeg'; | |
//get the image data | |
$image = file_get_contents($gravatarURL); | |
//write the image to the filesystem | |
$folder = Folder::find_or_make('/Uploads/User-Profile-Pics/'); | |
file_put_contents(ASSETS_PATH . '/Uploads/User-Profile-Pics/'.$gravatarEmailHash.'.'.$ext, $image); | |
//set our ProfileImage filename | |
$filename = ASSETS_DIR . '/Uploads/User-Profile-Pics/'.$gravatarEmailHash.'.'.$ext; | |
//Check if an Image record already exists for this Filename in the database. | |
//If one already exists, use that image as our ProfileImage. | |
if($profilePic = Image::get()->filter(array('Filename' => $filename))->first()) { | |
$this->ProfileImageID = $profilePic->ID; | |
} else { | |
//create a new Image DataObject with the details of this new image and save record to database | |
$profilePic = new Image(); | |
$profilePic->Filename = ASSETS_DIR . '/Uploads/User-Profile-Pics/'.$gravatarEmailHash.'.'.$ext; | |
$profilePic->Title = $gravatarEmailHash; | |
$profilePic->ParentID = $folder->ID; | |
$profilePic->write(); | |
$this->ProfileImageID = $profilePic->ID; | |
} | |
} // OK | |
// else if (strpos($headers[0],'404')) { | |
// //echo "No Gravatar"; | |
// } // Not Found | |
} | |
parent::onBeforeWrite(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment