<?php
class fetchAvatar
{
    protected $userId;
    protected $avatarSrc;

    public function __construct($options = array()) {

        if ( isset($options["userId"]) ) {

            $this->userId = $options["userId"];

        } else {

            $current_user = wp_get_current_user();
            $this->userId = $current_user->ID;
        }

        $this->avatarSrc = isset($options["avatarSrc"]) ? $options["avatarSrc"] : "";
    }

    public function setUserId($value) {

        $this->userId = $value;
    }

    public function setAvatarSrc($value) {

        $this->avatarSrc = $value;
    }

    public function fetch() {

        global $bp;
        $user = get_userdata($this->userId);

        $userNicename = $user->userdata->user_nicename;

        $currentAvatar = bp_core_fetch_avatar( array( 'item_id' => $this->userId, 'type' => 'full', 'width' => 32, 'height' => 32  ) );
        $currentAvatarSrc = substr($currentAvatar, strpos($currentAvatar,' src="')+6, strpos($currentAvatar,' alt="')-11);
        $currentAvatarSrc = str_replace(home_url()."/wp-content/uploads", bp_core_avatar_upload_path(), $currentAvatarSrc);

        $targetPath =  bp_core_avatar_upload_path()."/avatars/".$this->userId."/";

        if (!file_exists($targetPath)) {

            mkdir($targetPath, 0777, true);
            chmod($targetPath, 0777);
        }

        $newAvatarNameSegments = explode("/", $this->avatarSrc);
        $newAvatarName = $newAvatarNameSegments[count($newAvatarNameSegments)-1];

        $newAvatarExt = ".png"; //default value

        if (strrpos($newAvatarName, ".") !== false) {

            if(in_array(substr($newAvatarName, strrpos($newAvatarName, ".")), array(".png",".gif",".jpeg",".jpg"))) {

                $newAvatarExt = substr($newAvatarName, strrpos($newAvatarName, "."));
            }
        }
        
        $newAvatarName = base64_encode(microtime());

        if(strpos($currentAvatarSrc,"default_avatar.jpg") !== false) {

            try {

                $newAvatarSrc = file_get_contents($this->avatarSrc);
                file_put_contents($targetPath.$newAvatarName."-bpfull".$newAvatarExt, $newAvatarSrc);
                file_put_contents($targetPath.$newAvatarName."-bpthumb".$newAvatarExt, $newAvatarSrc);
                /*wp_redirect(home_url()."/members/".$userNicename."/profile/change-avatar");
                die;*/
                return true;

            } catch(Exception $e) {

                echo "Error: ".$e."<br />";
            }

        } else {

            try {

                if (file_exists($currentAvatarSrc)) {

                    unlink($currentAvatarSrc);
                }

                $currentAvatarThumbSrc = str_replace("-bpfull","-bpthumb",$currentAvatarSrc);

                if (file_exists($currentAvatarThumbSrc)) {

                    unlink($currentAvatarThumbSrc);
                }

                //var_dump($this->avatarSrc);
                $newAvatarSrc = file_get_contents($this->avatarSrc);
                
                //var_dump($newAvatarSrc);
                
                file_put_contents($targetPath.$newAvatarName."-bpfull".$newAvatarExt, $newAvatarSrc);
                file_put_contents($targetPath.$newAvatarName."-bpthumb".$newAvatarExt, $newAvatarSrc);
                return true;

            } catch(Exception $e) {

                echo "Error: ".$e."<br />";
            }
        }
    
        return true;
    }
} //end fetchAvatar

if (isset($_POST["getavatar"]) and $_POST["getavatar"] != "") {

    require_once(dirname(__FILE__).'/../../../../../../wp-blog-header.php');
    
    $newAvatar = new fetchAvatar();
    $newAvatar->setAvatarSrc($_POST["getavatar"]);
    
    if ($newAvatar->fetch()) {
    
        wp_redirect(home_url()."/members/".$userNicename."/profile/change-avatar");
        return;
    }
}