Editor::image_process( array $matches )

Description #

Callback called in @see ::pre_get.

Checks if current image is in anspress-temp directory and if so then moves it to anspress-uploads directory and return new img tag with new src.

Parameters #

  • $matches
    array (Required) Regex matches.

Source #

File: lib/form/class-editor.php

	public function image_process( $matches ) {
		if ( false === strpos( $matches[1], 'anspress-temp/' ) ) {
			return $matches[0];
		}

		$files = anspress()->session->get( 'files' );

		$uploads   = wp_upload_dir();
		$basename  = basename( $matches[1] );
		$temp_file = $uploads['basedir'] . '/anspress-temp/' . $basename;

		// Make sure WP_Filesystem is loaded.
		if ( ! function_exists( 'WP_Filesystem' ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
		}

		// Initialize WP_Filesystem.
		if ( ! WP_Filesystem() ) {
			// Unable to initialize WP_Filesystem, handle error accordingly.
			return;
		}

		global $wp_filesystem;

		// Check temp file is in anspress-temp directory.
		if ( ! file_exists( $temp_file ) ) {
			$this->add_error( 'fields-error', __( 'Sorry an error occured while processing your image, please remove it and insert again', 'anspress-question-answer' ) );
		} else {
			$upload_dir = $uploads['basedir'] . '/anspress-uploads/';

			// Make dir if not exists.
			if ( ! file_exists( $upload_dir ) ) {
				$wp_filesystem->mkdir( $upload_dir );
			}

			// Check file in session and then move.
			if ( in_array( $basename, $files, true ) ) {
				$this->images[] = $basename;

				$newfile = $upload_dir . "/$basename";

				$new_file_url = $uploads['baseurl'] . "/anspress-uploads/$basename";
				$wp_filesystem->move( $uploads['basedir'] . "/anspress-temp/$basename", $newfile );

				return '<img src="' . esc_url( $new_file_url ) . '" />';
			}
		}

		return false;
	}

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