@@ -53,6 +53,31 @@ public function assignToUserFromExistingData(User $user, string $imageData, stri
5353 }
5454 }
5555
56+ /**
57+ * Assign a new avatar image to the given user by fetching from a remote URL.
58+ */
59+ public function assignToUserFromUrl (User $ user , string $ avatarUrl , ?string $ accessToken = null ): void
60+ {
61+ // Quickly skip invalid or non-HTTP URLs
62+ if (!$ avatarUrl || !str_starts_with ($ avatarUrl , 'http ' )) {
63+ return ;
64+ }
65+
66+ try {
67+ $ this ->destroyAllForUser ($ user );
68+ $ imageData = $ this ->getAvatarImageData ($ avatarUrl , $ accessToken );
69+ $ avatar = $ this ->createAvatarImageFromData ($ user , $ imageData , 'png ' );
70+ $ user ->avatar ()->associate ($ avatar );
71+ $ user ->save ();
72+ } catch (Exception $ e ) {
73+ Log::error ('Failed to save user avatar image from URL ' , [
74+ 'exception ' => $ e ,
75+ 'url ' => $ avatarUrl ,
76+ 'user_id ' => $ user ->id ,
77+ ]);
78+ }
79+ }
80+
5681 /**
5782 * Destroy all user avatars uploaded to the given user.
5883 */
@@ -105,15 +130,21 @@ protected function createAvatarImageFromData(User $user, string $imageData, stri
105130 }
106131
107132 /**
108- * Gets an image from url and returns it as a string of image data.
133+ * Gets an image from a URL (public or private) and returns it as a string of image data.
109134 *
110135 * @throws HttpFetchException
111136 */
112- protected function getAvatarImageData (string $ url ): string
137+ protected function getAvatarImageData (string $ url, ? string $ accessToken = null ): string
113138 {
114139 try {
140+ $ headers = [];
141+ if (!empty ($ accessToken )) {
142+ $ headers ['Authorization ' ] = 'Bearer ' . $ accessToken ;
143+ }
144+
115145 $ client = $ this ->http ->buildClient (5 );
116- $ response = $ client ->sendRequest (new Request ('GET ' , $ url ));
146+ $ response = $ client ->sendRequest (new Request ('GET ' , $ url , $ headers ));
147+
117148 if ($ response ->getStatusCode () !== 200 ) {
118149 throw new HttpFetchException (trans ('errors.cannot_get_image_from_url ' , ['url ' => $ url ]));
119150 }
0 commit comments