# plus-webp/1.07/lib/class-pluswebp.php

Plus WebP or AVIF, version 1.07. 289 lines.

- Page: https://pluginprobe.com/plugins/plus-webp/1.07/code/lib/class-pluswebp.php
- Raw: https://pluginprobe.com/plugins/plus-webp/1.07/raw/lib/class-pluswebp.php
- Modified: 2020-02-19T23:17:58+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/plus-webp/1.07/code/lib/class-pluswebp.php#L10-L20`.

```php
<?php
/**
 * Plus WebP
 *
 * @package    Plus WebP
 * @subpackage PlusWebp Main function
/*  Copyright (c) 2019- Katsushi Kawamori (email : dodesyoswift312@gmail.com)
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; version 2 of the License.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

$pluswebp = new PlusWebp();

/** ==================================================
 * Class Main function
 *
 * @since 1.00
 */
class PlusWebp {

	/** ==================================================
	 * Dir
	 *
	 * @var $upload_dir DIR.
	 */
	private $upload_dir;
	/** ==================================================
	 * Dir
	 *
	 * @var $upload_url URL.
	 */
	private $upload_url;
	/** ==================================================
	 * Dir
	 *
	 * @var $upload_path PATH.
	 */
	private $upload_path;

	/** ==================================================
	 * Construct
	 *
	 * @since 1.00
	 */
	public function __construct() {

		list( $this->upload_dir, $this->upload_url, $this->upload_path ) = $this->upload_dir_url_path();

		add_filter( 'wp_generate_attachment_metadata', array( $this, 'generate_webp' ), 10, 2 );

	}

	/** ==================================================
	 * Webp generate
	 *
	 * @param array $metadata  metadata.
	 * @param int   $attachment_id  ID.
	 * @return array $metadata  metadata.
	 * @since 1.00
	 */
	public function generate_webp( $metadata, $attachment_id ) {

		$pluswebp_settings = get_option( 'pluswebp' );
		$replace           = $pluswebp_settings['replace'];

		$mime_type = get_post_mime_type( $attachment_id );
		if ( 'image/jpeg' === $mime_type || 'image/png' === $mime_type || 'image/bmp' === $mime_type || 'image/gif' === $mime_type ) {
			$metadata_webp         = $metadata;
			$file_webp             = $this->change_ext( $metadata['file'], 'webp' );
			$metadata_webp['file'] = $file_webp;
			foreach ( (array) $metadata['sizes'] as $key => $value ) {
				$file_thumb      = $value['file'];
				$file_thumb_webp = $this->change_ext( $file_thumb, 'webp' );
				$path            = $this->upload_dir . '/' . dirname( $file_webp ) . '/';
				$url             = $this->upload_url . '/' . dirname( $file_webp ) . '/';
				$ret             = $this->create_webp( $path . $file_thumb, $mime_type, $path . $file_thumb_webp );
				if ( $ret ) {
					$metadata_webp['sizes'][ $key ]['file']      = $file_thumb_webp;
					$metadata_webp['sizes'][ $key ]['mime-type'] = 'image/webp';
					if ( $replace ) {
						unlink( $path . $file_thumb );
						$this->change_db( $url . $file_thumb, $url . $file_thumb_webp );
					}
				}
			}

			$ret = $this->create_webp( $this->upload_dir . '/' . $metadata['file'], $mime_type, $this->upload_dir . '/' . $file_webp );
			if ( $ret ) {
				if ( $replace ) {
					$up_post = array(
						'ID'             => $attachment_id,
						'guid'           => $this->upload_url . '/' . $file_webp,
						'post_mime_type' => 'image/webp',
					);
					wp_update_post( $up_post );
					update_post_meta( $attachment_id, '_wp_attached_file', $file_webp );
					/* for bulk generate */
					update_post_meta( $attachment_id, '_wp_attachment_metadata', $metadata_webp );
					/* delete org file */
					unlink( $this->upload_dir . '/' . $metadata['file'] );
					/* Replace */
					$this->change_db( $this->upload_url . '/' . $metadata['file'], $this->upload_url . '/' . $file_webp );
					/* for hook */
					$metadata = $metadata_webp;
				} else {
					$post       = get_post( $attachment_id );
					$title      = get_the_title( $post );
					$attachment = array(
						'guid'           => $this->upload_url . '/' . $file_webp,
						'post_mime_type' => 'image/webp',
						'post_title'     => $title,
						'post_content'   => '',
						'post_status'    => 'inherit',
					);
					$attach_id  = wp_insert_attachment( $attachment, $this->upload_dir . '/' . $file_webp );
					wp_update_attachment_metadata( $attach_id, $metadata_webp );

					$author      = get_userdata( $post->post_author );
					$userid      = $author->ID;
					$postdate    = get_the_date( 'Y-m-d H:i:s', $attachment_id );
					$postdategmt = get_gmt_from_date( $postdate );
					$up_post     = array(
						'ID'                => $attach_id,
						'post_author'       => $userid,
						'post_date'         => $postdate,
						'post_date_gmt'     => $postdategmt,
						'post_modified'     => $postdate,
						'post_modified_gmt' => $postdategmt,
					);
					wp_update_post( $up_post );
				}
			}
		}

		return $metadata;

	}

	/** ==================================================
	 * Webp create
	 *
	 * @param string $filename  input filename for pictures.
	 * @param string $mime_type  mimetype.
	 * @param string $filename_webp  output filename for webp.
	 * @return bool $ret create bool.
	 * @since 1.00
	 */
	private function create_webp( $filename, $mime_type, $filename_webp ) {

		if ( ! file_exists( $filename ) ) {
			return false;
		}
		if ( file_exists( $filename_webp ) ) {
			return false;
		}

		$pluswebp_settings = get_option( 'pluswebp' );
		@set_time_limit( 60 );

		$ret = false;
		switch ( $mime_type ) {
			case 'image/jpeg':
				$src = imagecreatefromjpeg( $filename );
				$img = imagecreatetruecolor( imagesx( $src ), imagesy( $src ) );
				imagefill( $img, 0, 0, imagecolorallocate( $img, 255, 255, 255 ) );
				imagealphablending( $img, true );
				break;
			case 'image/png':
				$src = imagecreatefrompng( $filename );
				$img = imagecreatetruecolor( imagesx( $src ), imagesy( $src ) );
				imagealphablending( $img, false );
				imagesavealpha( $img, true );
				break;
			case 'image/bmp':
				$src = imagecreatefrombmp( $filename );
				$img = imagecreatetruecolor( imagesx( $src ), imagesy( $src ) );
				break;
			case 'image/gif':
				$src = imagecreatefromgif( $filename );
				$img = imagecreatetruecolor( imagesx( $src ), imagesy( $src ) );
				$bgcolor = imagecolorallocatealpha( $img, 0, 0, 0, 127 );
				imagefill( $img, 0, 0, $bgcolor );
				imagecolortransparent( $img, $bgcolor );
				break;
		}

		imagecopy( $img, $src, 0, 0, 0, 0, imagesx( $src ), imagesy( $src ) );
		imagedestroy( $src );
		$ret = imagewebp( $img, $filename_webp, $pluswebp_settings['quality'] );
		imagedestroy( $img );

		return $ret;

	}

	/** ==================================================
	 * Change ext
	 *
	 * @param string $before_file_name  before_file_name.
	 * @param string $ext  ext.
	 * @return array $after_file_name  after_file_name.
	 * @since 1.00
	 */
	private function change_ext( $before_file_name, $ext ) {

		$exts            = explode( '.', $before_file_name );
		$before_ext      = '.' . end( $exts );
		$after_ext       = '.' . $ext;
		$after_file_name = str_replace( $before_ext, $after_ext, $before_file_name );

		return $after_file_name;

	}

	/** ==================================================
	 * Change DB
	 *
	 * @param string $before_url  before_url.
	 * @param string $after_url  after_url.
	 * @since 1.00
	 */
	private function change_db( $before_url, $after_url ) {

		global $wpdb;

		/* Replace */
		$wpdb->query(
			$wpdb->prepare(
				"UPDATE `$wpdb->posts` SET post_content = replace(post_content, %s, %s)",
				$before_url,
				$after_url
			)
		);

	}

	/** ==================================================
	 * Upload Path
	 *
	 * @return array $upload_dir,$upload_url,$upload_path  uploadpath.
	 * @since 1.00
	 */
	public function upload_dir_url_path() {

		$wp_uploads = wp_upload_dir();

		$relation_path_true = strpos( $wp_uploads['baseurl'], '../' );
		if ( $relation_path_true > 0 ) {
			$relationalpath = substr( $wp_uploads['baseurl'], $relation_path_true );
			$basepath       = substr( $wp_uploads['baseurl'], 0, $relation_path_true );
			$upload_url     = $this->realurl( $basepath, $relationalpath );
			$upload_dir     = wp_normalize_path( realpath( $wp_uploads['basedir'] ) );
		} else {
			$upload_url = $wp_uploads['baseurl'];
			$upload_dir = wp_normalize_path( $wp_uploads['basedir'] );
		}

		if ( is_ssl() ) {
			$upload_url = str_replace( 'http:', 'https:', $upload_url );
		}

		if ( $relation_path_true > 0 ) {
			$upload_path = $relationalpath;
		} else {
			$upload_path = str_replace( site_url( '/' ), '', $upload_url );
		}

		$upload_dir  = untrailingslashit( $upload_dir );
		$upload_url  = untrailingslashit( $upload_url );
		$upload_path = untrailingslashit( $upload_path );

		return array( $upload_dir, $upload_url, $upload_path );

	}

}



```
