Check for an avatar uploaded to the site, resort to gravatar if none exists, resort to no user image if no gravatar exists

@return string
357967
public function gravatar()
    {
        // Check for valid gravatar
        $gravCheck = 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?d=404';
        $response  = get_headers($gravCheck);

        // If a valid gravatar URL is found, use the gravatar image
        if ($response[0] != "HTTP/1.0 404 Not Found"){
            return 'http://www.gravatar.com/avatar/'. md5( strtolower( trim( $this->email ) ) ) .'.png?s=200&d=blank';
        }

        // If no other image is set, use the default
        return '/img/no_user.png';
    }
419323
public function avatar($width = null, $height = null,  $returnGravatarIfNotFound = false)
    {
        if($this->profileimage) {
            if(!$width && !$height) {
                return url($this->profileimage->url);
            }else{
                return $this->profileimage->thumb($width, $height, $this->profileimage);
            }
        }

        if($returnGravatarIfNotFound && $this->gravatar) {
            return $this->gravatar;
        }

        return;
    }
626356
public function checkGdInfo()
    {
        $iModStat = extension_loaded('gd') ? 1 : 0;
        $iModStat = function_exists('imagecreatetruecolor') ? 2 : $iModStat;
        $iModStat = function_exists('imagecreatefromgif') ? $iModStat : 0;
        $iModStat = function_exists('imagecreatefromjpeg') ? $iModStat : 0;
        $iModStat = function_exists('imagecreatefrompng') ? $iModStat : 0;

        return $iModStat;
    }
115437
public function filterBestVotedImage()
    {
        $currentImage = null;
        $voteAverage  = -1;

        /**
         * @var $image Image
         */
        foreach ($this->data as $image) {
            if ($image->getVoteAverage() > $voteAverage) {
                $voteAverage  = $image->getVoteAverage();
                $currentImage = $image;
            }
        }

        return $currentImage;
    }
611522
public function getRaw()
    {
        $url = $this->_gravatar->generateUrl('profile', $this->_gravatar->getEmail()).'.php';

        if (is_null($this->_data)) {
            // Let's make a quick check to see if the user exists
            // we'll throw an exception if a 404 is returned
            $h = get_headers($url, 1)[0];
            $code = substr($h, strrpos($h, '404'), strlen($h));

            if ($code == '404 Not Found') {
                throw new \Exception('404 Error code was thrown. Perhaps invalid email?');
            }

            // No error? K! Get the contents ;)
            $this->_data = file_get_contents($url);
        }

        return $this->_data;
    }
528774
public function matchesRequest()
    {
        $matches = $this->event->filter(function ($message) {
            return array_key_exists('body', $message) ||
            array_key_exists('picUrl', $message) ||
            array_key_exists('stickerUrl', $message) ||
            array_key_exists('videoUrl', $message);
        })->isNotEmpty();

        return $matches && ! empty($this->headers['x-kik-username']);
    }
1145148
public static function getCanPurge(): bool
    {
        if (!isset(self::$canPurge)) {
            /** @var ConfigModel $settings */
            $config = ImagerService::getConfig();
            
            // No Imgix config, no purging
            $imgixConfigArr = $config->getSetting('imgixConfig');
            if (!$imgixConfigArr || !\is_array($imgixConfigArr) || empty($imgixConfigArr)) {
                self::$canPurge = false;
                return false;
            }
            
            // Make sure there's at least one profile that is not a web proxy and that is not excluded from purging
            $hasApiKey = !!$config->getSetting('imgixApiKey');
            $hasPurgableProfile = false;
            foreach ($imgixConfigArr as $profile => $imgixConfig) {
                $imgixConfig = new ImgixSettings($imgixConfig);
                $hasApiKey = $hasApiKey || !!$imgixConfig->apiKey;
                $hasPurgableProfile = $hasPurgableProfile || (!$imgixConfig->sourceIsWebProxy && !$imgixConfig->excludeFromPurge);
                if ($hasApiKey && $hasPurgableProfile) {
                    break;
                }
            }
            
            self::$canPurge = $hasApiKey && $hasPurgableProfile;
        }
        
        return self::$canPurge;
    }
1331622
public function actionForum()
    {
        $user = User::findMe();
        $model = Meta::find()->where(['user_id' => $user->id])->limit(1)->one();
        if (empty($model)) {
            $model = new Meta();
        }

        if ($model->load(Yii::$app->request->post())) {
            $model->user_id = $user->id;
            $uploadAvatar = false;
            $path = Yii::getAlias('@webroot/avatars');
            $model->image = UploadedFile::getInstance($model, 'image');
            if ($model->validate()) {
                if ($model->gravatar && empty($user->email)) {
                    $model->addError('gravatar', Yii::t('podium/view', 'You need email address set to use Gravatar.'));
                } else {
                    if ($model->image) {
                        $folderExists = true;
                        if (!file_exists($path)) {
                            if (!FileHelper::createDirectory($path)) {
                                $folderExists = false;
                                Log::error('Error while creating avatars folder', null, __METHOD__);
                                $this->error(Yii::t('podium/flash', 'Sorry! There was an error while creating the avatars folder. Contact administrator about this problem.'));
                            }
                        }
                        if ($folderExists) {
                            $oldAvatarPath = $path . DIRECTORY_SEPARATOR . $model->avatar;
                            if (!empty($model->avatar) && file_exists($oldAvatarPath)) {
                                if (!unlink($oldAvatarPath)) {
                                    Log::error('Error while deleting old avatar image', null, __METHOD__);
                                }
                            }
                            $model->avatar = Yii::$app->security->generateRandomString() . '.' . $model->image->getExtension();
                            $uploadAvatar = true;
                        }
                    }
                    if ($model->save(false)) {
                        if ($uploadAvatar) {
                            if (!$model->image->saveAs($path . DIRECTORY_SEPARATOR . $model->avatar)) {
                                Log::error('Error while saving avatar image', null, __METHOD__);
                                $this->error(Yii::t('podium/flash', 'Sorry! There was an error while uploading the avatar image. Contact administrator about this problem.'));
                            }
                        }
                        Log::info('Profile updated', $model->id, __METHOD__);
                        $this->success(Yii::t('podium/flash', 'Your profile details have been updated.'));
                        return $this->refresh();
                    }
                }
            }
        }
        return $this->render('forum', ['model' => $model, 'user' => $user]);
    }
707820
public function index()
    {
        /**
         * Check the request headers; avoid hitting the disk at all if possible. If
         * the Etag matches then send a Not-Modified header and terminate execution.
         */

        if ($this->serveNotModified($this->cdnCacheFile)) {
            return;
        }

        // --------------------------------------------------------------------------

        /**
         * The browser does not have a local cache (or it's out of date) check the cache
         * to see if this image has been processed already; serve it up if it has.
         */

        if (file_exists($this->cdnCacheDir . $this->cdnCacheFile)) {

            $this->serveFromCache($this->cdnCacheFile);

        } else {

            /**
             * Cache object does not exist, fetch the original, process it and save a
             * version in the cache bucket.
             */

            //  Which original are we using?
            switch ($this->sex) {

                case 'female':
                case 'woman':
                case 'f':
                case 'w':

                    $src = $this->avatarFemale;
                    break;

                case 'male':
                case 'man':
                case 'm':

                    $src = $this->avatarMale;
                    break;

                case 'neutral':
                default:

                    $src = $this->avatarNeutral;
                    break;
            }

            $width  = $this->width * $this->retinaMultiplier;
            $height = $this->height * $this->retinaMultiplier;

            if (file_exists($src)) {

                //  Object exists, time for manipulation fun times :>

                //  Set some PHPThumb options
                $options             = [];
                $options['resizeUp'] = true;

                // --------------------------------------------------------------------------

                //  Perform the resize
                $PHPThumb = new PHPThumb\GD($src, $options);
                $PHPThumb->adaptiveResize($width, $height);

                // --------------------------------------------------------------------------

                //  Save local version and serve
                $PHPThumb->save($this->cdnCacheDir . $this->cdnCacheFile);
                $this->serveFromCache($this->cdnCacheFile);

            } else {
                //  This object does not exist.
                Factory::service('Logger')->line('CDN: Blank Avatar: File not found; ' . $src);
                return $this->serveBadSrc([
                    'width'  => $width,
                    'height' => $height,
                ]);
            }
        }
    }
147724
public function img()
    {
        // Check for an existing Image relation
        if (($image = $this->parentImg($this->inputName()))
            && $image->exists) {

            // If the Image represents a default image, but doesn't match the current
            // item from the config, trash the current one and build the new default
            // image.
            if ($replacement = $this->getReplacementImage($image)) {
                return $replacement;
            }

            // Return the found image
            return $image;
        }

        // Else return a default image
        return $this->defaultImage();
    }
589502
public function check()
    {
        $attributes = $this->getInputAttributes();
        if (array_key_exists('name', $attributes)) {
            $inputName = $attributes['name'];
        } else {
            $inputName = static::DEFAULT_INPUT_NAME;
        }
        $checkCode = $this->request->get($inputName);
        if (!is_string($checkCode)) {
            $checkCode = '';
        }

        return $this->securimage->check($checkCode);
    }
629942
public function actionProfile() {

		// Find Model
		$model = Yii::$app->core->getUser();

		// Avatar
		$avatar = $model->avatar;

		// Address
		$address = $model->primaryAddress;

		if( empty( $address ) ) {

			$address = $this->addressService->getModelObject();
		}

		// Clear Sidebar
		$this->sidebar = [];

		$genderMap = $this->optionService->getIdNameMapByCategorySlug( CoreGlobal::CATEGORY_GENDER, [ 'default' => true ] );

		$countryMap		= Yii::$app->factory->get( 'countryService' )->getIdNameMap();
		$countryId		= isset( $address->country ) ? $address->country->id : array_keys( $countryMap )[ 0 ];
		$provinceMap	= Yii::$app->factory->get( 'provinceService' )->getMapByCountryId( $countryId, [ 'default' => true, 'defaultValue' => Yii::$app->core->provinceLabel ] );
		$provinceId		= isset( $address->province ) ? $address->province->id : array_keys( $provinceMap )[ 0 ];
		$regionMap		= Yii::$app->factory->get( 'regionService' )->getMapByProvinceId( $provinceId, [ 'default' => true, 'defaultValue' => Yii::$app->core->regionLabel ] );

		return $this->render( 'profile', [
			'model' => $model,
			'avatar' => $avatar,
			'address' => $address,
			'genderMap' => $genderMap,
			'countryMap' => $countryMap,
			'provinceMap' => $provinceMap,
			'regionMap' => $regionMap
		]);
	}
286309
public function avatarAction ()
    {
        $finder = new Finder();
        $result = array();
        $finder->files()->in(__DIR__.'/../Resources/public/avatar')->name('*.png');
        foreach ($finder as $files) {
            $result[$files->getRelativePath()][] = $files->getRelativePathname();
        }
        $user = $this->getUser();
        $gravatar = new Gravatar();
        $gravatar->setAvatarSize(150);
        return $this->render('OlixSecurityBundle:Profile:avatar.html.twig', array(
            'avatars' => $result,
            'gravatar' => $gravatar->get($user->getEmail()),
        ));
    }
1370134
public String getOldAvatarUrl()
    {
        return previous == null ? null : String.format(AVATAR_URL, getSelfUser().getId(), previous, previous.startsWith("a_") ? ".gif" : ".png");
    }
769002
public function getOriginalImage()
    {
        if ($this->_originalImage == null) {
            $this->_originalImage = Yii::$app->getPath()->getTempPath() . DIRECTORY_SEPARATOR . $this->getUser()->id . '_avatar.jpg';
        }
        return $this->_originalImage;
    }
517380
public function ProcessAvatars() {
      $UploadImage = new Gdn_UploadImage();
      $UserData = $this->SQL->Select('u.Photo')->From('User u')->Where('u.Photo is not null')->Get();
      
      // Make sure the avatars folder exists.
      if (!file_exists(PATH_UPLOADS.'/userpics'))
         mkdir(PATH_UPLOADS.'/userpics');
      
      // Get sizes
      $ProfileHeight = C('Garden.Profile.MaxHeight', 1000);
      $ProfileWidth = C('Garden.Profile.MaxWidth', 250);
      $ThumbSize = C('Garden.Thumbnail.Size', 40);
      
      // Temporarily set maximum quality
      SaveToConfig('Garden.UploadImage.Quality', 100, FALSE);
      
      // Create profile and thumbnail sizes
      foreach ($UserData->Result() as $User) {
         try {
            $Image = PATH_ROOT . DS . 'uploads' . DS . GetValue('Photo', $User);
            $ImageBaseName = pathinfo($Image, PATHINFO_BASENAME);            
            
            // Save profile size
            $UploadImage->SaveImageAs(
               $Image,
               PATH_UPLOADS.'/userpics/p'.$ImageBaseName,
               $ProfileHeight,
               $ProfileWidth
            );
            
            // Save thumbnail size
            $UploadImage->SaveImageAs(
               $Image,
               PATH_UPLOADS.'/userpics/n'.$ImageBaseName,
               $ThumbSize,
               $ThumbSize,
               TRUE
            );
         } catch (Exception $ex) { }
      }
   }
119907
public function getAvatarImage(): ?ImageMedium
    {
        $avatars = $this->get('avatar');
        if (\is_array($avatars) && $avatars) {
            $avatar = array_shift($avatars);

            $media = $this->getMedia();
            $name = $avatar['name'] ?? null;

            $image = $name ? $media[$name] : null;
            if ($image instanceof ImageMedium) {
                return $image;
            }
        }

        return null;
    }