AvatarRoute.php
5 years ago
LocationRoute.php
5 years ago
ProfileRoute.php
5 years ago
Tab.php
5 years ago
AvatarRoute.php
98 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\DonorDashboards\Tabs\EditProfileTab; |
| 4 | |
| 5 | use WP_REST_Request; |
| 6 | use Give\DonorDashboards\Tabs\Contracts\Route as RouteAbstract; |
| 7 | use WP_REST_Response; |
| 8 | |
| 9 | /** |
| 10 | * @since 2.10.3 |
| 11 | */ |
| 12 | class AvatarRoute extends RouteAbstract { |
| 13 | |
| 14 | /** |
| 15 | * @inheritdoc |
| 16 | */ |
| 17 | public function endpoint() { |
| 18 | return 'avatar'; |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * @inheritdoc |
| 23 | */ |
| 24 | public function args() { |
| 25 | return []; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * @inheritDoc |
| 30 | * |
| 31 | * @return array |
| 32 | */ |
| 33 | public function handleRequest( WP_REST_Request $request ) { |
| 34 | |
| 35 | if ( ! ( is_array( $_POST ) && is_array( $_FILES ) ) ) { |
| 36 | return new WP_REST_Response( |
| 37 | [ |
| 38 | 'status' => 400, |
| 39 | 'response' => 'missing_files', |
| 40 | 'body_response' => [ |
| 41 | 'message' => __( 'No files were included in request for upload.', 'give' ), |
| 42 | ], |
| 43 | ] |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | // Delete existing Donor profile avatar attachment |
| 48 | if ( give()->donorDashboard->getAvatarId() ) { |
| 49 | wp_delete_attachment( give()->donorDashboard->getAvatarId(), true ); |
| 50 | } |
| 51 | |
| 52 | if ( ! function_exists( 'wp_handle_upload' ) ) { |
| 53 | require_once( ABSPATH . 'wp-admin/includes/file.php' ); |
| 54 | } |
| 55 | |
| 56 | foreach ( $_FILES as $file ) { |
| 57 | $upload = wp_handle_upload( |
| 58 | $file, |
| 59 | [ |
| 60 | 'test_form' => false, |
| 61 | ] |
| 62 | ); |
| 63 | |
| 64 | if ( isset( $upload['url'] ) ) { |
| 65 | $path = $upload['url']; |
| 66 | |
| 67 | // Check the type of file. We'll use this as the 'post_mime_type'. |
| 68 | $filetype = wp_check_filetype( basename( $path ), null ); |
| 69 | |
| 70 | // Prepare an array of post data for the attachment. |
| 71 | $attachment = [ |
| 72 | 'guid' => $path, |
| 73 | 'post_mime_type' => $filetype['type'], |
| 74 | 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $path ) ), |
| 75 | 'post_content' => '', |
| 76 | 'post_status' => 'inherit', |
| 77 | ]; |
| 78 | |
| 79 | // Insert the attachment. |
| 80 | $attachmentId = wp_insert_attachment( $attachment, $path ); |
| 81 | |
| 82 | // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it. |
| 83 | require_once( ABSPATH . 'wp-admin/includes/image.php' ); |
| 84 | |
| 85 | // Generate the metadata for the attachment, and update the database record. |
| 86 | $attachmentData = wp_generate_attachment_metadata( $attachmentId, $path ); |
| 87 | wp_update_attachment_metadata( $attachmentId, $attachmentData ); |
| 88 | |
| 89 | return [ |
| 90 | 'id' => $attachmentId, |
| 91 | ]; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | } |
| 96 | |
| 97 | } |
| 98 |