AnsPress_Uploader::image_upload()

Description #

Ajax callback for ap_image_upload. Process image_upload form.

Changelog #

VersionDescription
4.1.8
4.1.13Introduced.

Source #

File: includes/upload.php

	public static function image_upload() {
		$form = anspress()->get_form( 'image_upload' );

		// Check if user have permission to upload tem image.
		if ( ! ap_user_can_upload() ) {
			ap_send_json(
				array(
					'success'  => false,
					'snackbar' => array(
						'message' => __( 'Sorry! you do not have permission to upload image.', 'anspress-question-answer' ),
					),
				)
			);
		}

		// Nonce check.
		if ( ! $form->is_submitted() ) {
			ap_ajax_json( 'something_wrong' );
		}

		$image_for = ap_sanitize_unslash( 'image_for', 'r' );
		$values    = $form->get_values();

		// Check for errors.
		if ( $form->have_errors() ) {
			ap_send_json(
				array(
					'success'       => false,
					'snackbar'      => array(
						'message' => __( 'Unable to upload image(s). Please check errors.', 'anspress-question-answer' ),
					),
					'form_errors'   => $form->errors,
					'fields_errors' => $form->get_fields_errors(),
				)
			);
		}

		$field = $form->find( 'image' );

		// Call save.
		$files = $field->save_cb();

		$new_arr = array();

		// Add a property to check if image or not.
		if ( ! empty( $files ) ) {
			$all_possible_images_ext = array( 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp' );

			foreach ( $files as $file_basename => $file_url ) {
				// Get file extension from file name.
				$ext = pathinfo( $file_basename, PATHINFO_EXTENSION );

				$new_arr[ $file_basename ] = array(
					'ext'      => $ext,
					'filename' => $file_basename,
					'is_image' => in_array( $ext, $all_possible_images_ext, true ),
					'url'      => $file_url,
				);
			}

			$files = $new_arr;
		}

		$res = array(
			'success'   => true,
			'action'    => 'ap_image_upload',
			'image_for' => $image_for,
			'snackbar'  => array( 'message' => __( 'Successfully uploaded image', 'anspress-question-answer' ) ),
			'files'     => $files,
		);

		// Send response.
		if ( is_array( $res ) ) {
			ap_send_json( $res );
		}

		ap_ajax_json( 'something_wrong' );
	}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment