Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
37.50% covered (danger)
37.50%
39 / 104
12.50% covered (danger)
12.50%
1 / 8
CRAP
n/a
0 / 0
jetpack_wpcom_maybe_convert_heif_to_jpg
55.17% covered (warning)
55.17%
32 / 58
0.00% covered (danger)
0.00%
0 / 1
11.41
jetpack_wpcom_maybe_log_heif_to_jpg
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
3.69
jetpack_wpcom_transparently_convert_heif_upload_to_jpg
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
20
jetpack_wpcom_add_heif_mimes_to_supported_sideload_types
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
jetpack_wpcom_add_heif_mimes_to_supported_upload_types
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
jetpack_wpcom_allow_heif_uploads_in_rest_api
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
jetpack_wpcom_add_heif_rest_api_filter
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
jetpack_wpcom_disable_heic_plupload_error
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * HEIF/HEIF support for WordPress.com sites.
4 *
5 * @package automattic/jetpack-mu-plugins
6 */
7
8/**
9 * Convert HEIF/HEIC uploads to JPEG.
10 *
11 * @param string $filename Path to the file.
12 * @return bool True if the file was converted, false otherwise.
13 */
14function jetpack_wpcom_maybe_convert_heif_to_jpg( $filename ) {
15    if ( ! class_exists( 'Photon_OpenCV' ) ) {
16        return false;
17    }
18
19    if ( empty( $filename ) ) {
20        jetpack_wpcom_maybe_log_heif_to_jpg(
21            array(
22                'message'  => 'file path is empty',
23                'severity' => 'error',
24            )
25        );
26        return false;
27    }
28
29    if ( ! file_exists( $filename ) ) {
30        jetpack_wpcom_maybe_log_heif_to_jpg(
31            array(
32                'message'  => sprintf( 'file does not exist: %s', $filename ),
33                'severity' => 'error',
34            )
35        );
36        return false;
37    }
38
39    $valid_magic_bytes = array(
40        'ftypheic',
41        'ftypheix',
42        'ftyphevc',
43        'ftypheim',
44        'ftypheis',
45        'ftyphevm',
46        'ftyphevs',
47        'ftypmif1',
48        'ftypmsf1',
49    );
50
51    // Read the first 8 bytes of the file.
52    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
53    $magic_bytes = file_get_contents( $filename, false, null, 4, 8 );
54    if ( ! in_array( $magic_bytes, $valid_magic_bytes, true ) ) {
55        return false;
56    }
57
58    // Log that we found a HEIF image.
59    jetpack_wpcom_maybe_log_heif_to_jpg(
60        array(
61            'message'  => sprintf( 'Found HEIF image: %s with magic bytes: %s', $filename, $magic_bytes ),
62            'severity' => 'info',
63        )
64    );
65
66    $img = new Photon_OpenCV();
67    try {
68        $img->readimage( $filename );
69    } catch ( Exception $e ) {
70        // Bad detection or malformed image
71        /** This action is documented in modules/widgets/social-media-icons.php */
72        do_action( 'jetpack_bump_stats_extras', 'heif2jpg', 'failed-to-read' );
73        jetpack_wpcom_maybe_log_heif_to_jpg(
74            array(
75                'message'    => sprintf( 'failed to read image: %s', $e->getMessage() ),
76                'error_code' => $e->getCode(),
77                'severity'   => 'error',
78            )
79        );
80        return false;
81    }
82
83    // photon-opencv drops a HEIC's metadata, so exiftool copies the AI marker across.
84    require_once __DIR__ . '/class-jetpack-wpcom-ai-marker.php';
85    $ai_marker           = new Jetpack_WPCOM_AI_Marker( 'heif2jpg_ai_marker' );
86    $digital_source_type = $ai_marker->read( $filename );
87
88    $img->setimageformat( 'jpg' );
89    // This should never fail
90    $img->writeimage( $filename );
91
92    if ( '' !== $digital_source_type ) {
93        $ai_marker->write( $filename, $digital_source_type );
94    }
95
96    return true;
97}
98
99/**
100 * Log information about HEIF/HEIC conversions.
101 *
102 * @param array $params The parameters to log.
103 *
104 * @return void
105 */
106function jetpack_wpcom_maybe_log_heif_to_jpg( $params = array() ) {
107
108    if ( ! file_exists( WP_CONTENT_DIR . '/lib/log2logstash/log2logstash.php' ) ) {
109        return;
110    }
111
112    require_once WP_CONTENT_DIR . '/lib/log2logstash/log2logstash.php';
113
114    $default = array(
115        'feature' => 'heif2jpg',
116        'blog_id' => get_current_blog_id(),
117    );
118
119    log2logstash( wp_parse_args( $params, $default ) );
120}
121
122/**
123 * Attempts to convert HEIF/HEIC uploads to JPEG.
124 *
125 * @param array $file The file array.
126 * @return array The file array.
127 */
128function jetpack_wpcom_transparently_convert_heif_upload_to_jpg( $file ) {
129    if ( ! class_exists( 'Photon_OpenCV' ) || ! $file ) {
130        return $file;
131    }
132
133    // $file only has `name` and `tmp_name` when sideloading
134    $original_size = filesize( $file['tmp_name'] );
135
136    if ( false === jetpack_wpcom_maybe_convert_heif_to_jpg( $file['tmp_name'] ) ) {
137        return $file;
138    }
139
140    // tmp_name is reused, cache needs to be cleared
141    clearstatcache();
142    $new_file = array(
143        'name'     => pathinfo( $file['name'], PATHINFO_FILENAME ) . '.jpg',
144        'type'     => 'image/jpeg',
145        'tmp_name' => $file['tmp_name'],
146        'error'    => 0,
147        'size'     => filesize( $file['tmp_name'] ),
148    );
149
150    /** This action is documented in modules/widgets/social-media-icons.php */
151    do_action( 'jetpack_bump_stats_extras', 'heif2jpg', 'conversions' );
152    /** This action is documented in modules/widgets/social-media-icons.php */
153    do_action( 'jetpack_bump_stats_extras', 'heif2jpg', 'bytes-added', $new_file['size'] - $original_size );
154
155    return $new_file;
156}
157add_filter( 'wp_handle_upload_prefilter', 'jetpack_wpcom_transparently_convert_heif_upload_to_jpg' );
158add_filter( 'wp_handle_sideload_prefilter', 'jetpack_wpcom_transparently_convert_heif_upload_to_jpg' );
159
160/**
161 * Add HEIF/HEIC to the list of supported mime types for sideloading.
162 *
163 * @param array $mimes The list of supported mime types.
164 * @return array The list of supported mime types.
165 */
166function jetpack_wpcom_add_heif_mimes_to_supported_sideload_types( $mimes ) {
167    if ( ! class_exists( 'Photon_OpenCV' ) ) {
168        return $mimes;
169    }
170    $mimes[] = 'image/heif';
171    $mimes[] = 'image/heic';
172    return $mimes;
173}
174add_filter( 'jetpack_supported_media_sideload_types', 'jetpack_wpcom_add_heif_mimes_to_supported_sideload_types' );
175
176/**
177 * Add HEIF/HEIC to the list of supported mime types for uploads.
178 *
179 * @param array $mimes The list of supported mime types.
180 * @return array The list of supported mime types.
181 */
182function jetpack_wpcom_add_heif_mimes_to_supported_upload_types( $mimes ) {
183    if ( ! class_exists( 'Photon_OpenCV' ) ) {
184        return $mimes;
185    }
186
187    $mimes['heif'] = 'image/heif';
188
189    // HEIC is supported by default, so maybe we don't need it anymore.
190    // See https://github.com/WordPress/wordpress-develop/blob/80b7747ef165dd5ed0150003a8c2f957f097609e/src/wp-includes/functions.php#L3416.
191    $mimes['heic'] = 'image/heic';
192    return $mimes;
193}
194add_filter( 'upload_mimes', 'jetpack_wpcom_add_heif_mimes_to_supported_upload_types' );
195
196/**
197 * Prevent WordPress from blocking HEIF/HEIC uploads in REST API.
198 *
199 * This allows HEIF/HEIC files to pass through the REST API validation
200 * so they can be converted to JPEG by our conversion filter.
201 *
202 * @param bool        $check_mime Whether to check the mime type.
203 * @param string|null $mime_type  The mime type being uploaded.
204 * @return bool
205 */
206function jetpack_wpcom_allow_heif_uploads_in_rest_api( $check_mime, $mime_type ) {
207    if ( wp_is_heic_image_mime_type( $mime_type ) ) {
208        return false;
209    }
210
211    return $check_mime;
212}
213
214/**
215 * Add the HEIF/HEIC upload filter on REST API initialization.
216 */
217function jetpack_wpcom_add_heif_rest_api_filter() {
218    add_filter( 'wp_prevent_unsupported_mime_type_uploads', 'jetpack_wpcom_allow_heif_uploads_in_rest_api', 10, 2 );
219}
220add_action( 'rest_api_init', 'jetpack_wpcom_add_heif_rest_api_filter' );
221
222/**
223 * Disable HEIC upload error in plupload settings for WordPress.com.
224 *
225 * @param array $defaults The default plupload settings.
226 * @return array The modified settings.
227 */
228function jetpack_wpcom_disable_heic_plupload_error( $defaults ) {
229    $defaults['heic_upload_error'] = false;
230    return $defaults;
231}
232add_filter( 'plupload_default_settings', 'jetpack_wpcom_disable_heic_plupload_error' );