Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.37% covered (success)
95.37%
103 / 108
72.73% covered (warning)
72.73%
8 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_WPCOM_AI_Marker
95.37% covered (success)
95.37%
103 / 108
72.73% covered (warning)
72.73%
8 / 11
42
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 read
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 write
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
3.71
 read_local
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 read_from_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
 read_c2pa
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
8.01
 run_tool
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
10
 stop
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 is_synthetic
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 log_error
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 bump_stat
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Reads and writes an image's AI marker with exiftool and c2patool.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8/**
9 * Reads an AI IPTC DigitalSourceType from XMP or C2PA, and writes it to XMP.
10 */
11class Jetpack_WPCOM_AI_Marker {
12
13    /**
14     * Limits the bytes of tool output to read to avoid exhausting PHP's memory on a huge manifest.
15     */
16    const MAX_OUTPUT = 262144;
17
18    /**
19     * The IPTC DigitalSourceTypes for AI or synthetic media to keep.
20     *
21     * @see https://cv.iptc.org/newscodes/digitalsourcetype/
22     */
23    const SYNTHETIC_TYPES = array(
24        'http://cv.iptc.org/newscodes/digitalsourcetype/trainedAlgorithmicMedia',
25        'http://cv.iptc.org/newscodes/digitalsourcetype/compositeWithTrainedAlgorithmicMedia',
26        'http://cv.iptc.org/newscodes/digitalsourcetype/compositeSynthetic',
27    );
28
29    /**
30     * The jetpack_bump_stats_extras group for this caller.
31     *
32     * @var string
33     */
34    private $stats_group;
35
36    /**
37     * The errors this request sent to Logstash, by blog, so a bulk job sends each one once.
38     *
39     * @var true[][]
40     */
41    private static $logged = array();
42
43    /**
44     * The tools that timed out or couldn't start in this request, so later saves don't wait on them again.
45     *
46     * @var true[]
47     */
48    private static $broken_tools = array();
49
50    /**
51     * Sets the stats group.
52     *
53     * @param string $stats_group The jetpack_bump_stats_extras group for this caller.
54     */
55    public function __construct( $stats_group ) {
56        $this->stats_group = $stats_group;
57    }
58
59    /**
60     * Reads the AI DigitalSourceType from a path or a URL.
61     *
62     * @param string $file Path or URL of the source image.
63     * @return string The type, or '' when the file has no AI type or the host has no exiftool.
64     */
65    public function read( $file ) {
66        // The marker is optional, so no error may stop the save.
67        try {
68            if ( ! jetpack_wpcom_ai_marker_tool_path( 'exiftool' ) ) {
69                return '';
70            }
71
72            return preg_match( '|^https?://|', $file )
73                ? $this->read_from_url( $file )
74                : $this->read_local( $file );
75        } catch ( Throwable $e ) {
76            // The class only: messages can hold file paths.
77            $this->log_error( 'read-error', array( 'error' => get_class( $e ) ) );
78            return '';
79        }
80    }
81
82    /**
83     * Writes the type with exiftool.
84     *
85     * @param string $filename            Path of the image.
86     * @param string $digital_source_type The type to write.
87     */
88    public function write( $filename, $digital_source_type ) {
89        try {
90            $exiftool = jetpack_wpcom_ai_marker_tool_path( 'exiftool' );
91            // Stops exiftool recording its version.
92            $output = $this->run_tool( 'exiftool', 'write', array( $exiftool, '-config', '', '-m', '-q', '-overwrite_original', '-XMP-x:XMPToolkit=', '-XMP-iptcExt:DigitalSourceType=' . $digital_source_type, $filename ) );
93        } catch ( Throwable $e ) {
94            $this->log_error( 'write-error', array( 'error' => get_class( $e ) ) );
95            return;
96        }
97
98        // run_tool() counts and logs a failed write.
99        if ( null !== $output ) {
100            $this->bump_stat( 'written' );
101        }
102    }
103
104    /**
105     * Reads the AI DigitalSourceType from XMP, then from C2PA when the file has a manifest.
106     *
107     * @param string $file Path of the source image.
108     * @return string The type, or '' when the file has no AI type.
109     */
110    private function read_local( $file ) {
111        $exiftool = jetpack_wpcom_ai_marker_tool_path( 'exiftool' );
112        // No config file: exiftool runs it as Perl.
113        $output              = (string) $this->run_tool( 'exiftool', 'read', array( $exiftool, '-config', '', '-m', '-S', '-XMP-iptcExt:DigitalSourceType', '-JUMBF:JUMDLabel', $file ) );
114        $digital_source_type = preg_match( '/^DigitalSourceType: (.*)$/m', $output, $match ) ? trim( $match[1] ) : '';
115        if ( self::is_synthetic( $digital_source_type ) ) {
116            return $digital_source_type;
117        }
118
119        return str_contains( $output, 'JUMDLabel: ' ) ? $this->read_c2pa( $file ) : '';
120    }
121
122    /**
123     * Core loads the source by URL when the file isn't on this host.
124     *
125     * @param string $url URL of the source image.
126     * @return string The type, or '' when the file has no AI type or the download fails.
127     */
128    private function read_from_url( $url ) {
129        require_once ABSPATH . 'wp-admin/includes/file.php';
130        $this->bump_stat( 'remote-source' );
131
132        $temp = download_url( $url, 10 );
133        if ( is_wp_error( $temp ) ) {
134            $this->log_error( 'download-failed', array( 'error' => $temp->get_error_code() ) );
135            return '';
136        }
137
138        try {
139            return $this->read_local( $temp );
140        } finally {
141            // wp_delete_file() hooks are for uploads.
142            unlink( $temp ); // phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink
143        }
144    }
145
146    /**
147     * Reads the active manifest first: c2patool lists manifests in no fixed order.
148     *
149     * @param string $file Path of the source image.
150     * @return string The type, or '' when there is no AI type or c2patool fails.
151     */
152    private function read_c2pa( $file ) {
153        $c2patool = jetpack_wpcom_ai_marker_tool_path( 'c2patool' );
154        $settings = __DIR__ . '/c2pa-settings.json';
155        // c2patool ignores a missing settings file, then fetches remote manifests.
156        if ( ! $c2patool || ! is_readable( $settings ) ) {
157            return '';
158        }
159
160        $store     = json_decode( (string) $this->run_tool( 'c2patool', 'read', array( $c2patool, '--settings', $settings, $file ) ), true );
161        $manifests = (array) ( $store['manifests'] ?? array() );
162        $active    = $store['active_manifest'] ?? '';
163        if ( isset( $manifests[ $active ] ) ) {
164            $manifests = array( $active => $manifests[ $active ] ) + $manifests;
165        }
166
167        foreach ( $manifests as $manifest ) {
168            foreach ( (array) ( $manifest['assertions'] ?? array() ) as $assertion ) {
169                foreach ( (array) ( $assertion['data']['actions'] ?? array() ) as $action ) {
170                    $digital_source_type = $action['digitalSourceType'] ?? '';
171                    if ( self::is_synthetic( $digital_source_type ) ) {
172                        $this->bump_stat( 'from-c2pa' );
173                        return $digital_source_type;
174                    }
175                }
176            }
177        }
178
179        return '';
180    }
181
182    /**
183     * Runs a tool without a shell, with a time limit: PHP's own limit ignores other programs.
184     *
185     * @param string   $name    exiftool or c2patool, for the error log.
186     * @param string   $step    'read' or 'write', for the error log.
187     * @param string[] $command The program and its arguments.
188     * @return string|null Its output, or null when it fails, times out or prints too much.
189     */
190    private function run_tool( $name, $step, array $command ) {
191        if ( isset( self::$broken_tools[ $name ] ) ) {
192            return null;
193        }
194
195        /**
196         * Filters how many seconds a tool may run.
197         *
198         * @since $$next-version$$
199         *
200         * @param int|float $seconds The time limit.
201         */
202        $deadline = microtime( true ) + (float) apply_filters( 'jetpack_wpcom_ai_marker_tool_time_limit', 2 );
203
204        // No stdin, so a tool can't wait for input.
205        $descriptors = array(
206            0 => array( 'null' ),
207            1 => array( 'pipe', 'w' ),
208            2 => array( 'null' ),
209        );
210        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_proc_open
211        $process = proc_open( $command, $descriptors, $pipes );
212        $tool    = array(
213            'tool' => $name,
214            'step' => $step,
215        );
216        if ( ! is_resource( $process ) ) {
217            self::$broken_tools[ $name ] = true;
218            $this->log_error( 'could-not-start', $tool );
219            return null;
220        }
221
222        // Non-blocking, so a read can't outlast the deadline.
223        stream_set_blocking( $pipes[1], false );
224        $output = '';
225        // Read while waiting, so a full pipe can't block the tool. The read after its exit gets the rest.
226        do {
227            usleep( 10000 );
228            $status  = proc_get_status( $process );
229            $output .= (string) stream_get_contents( $pipes[1], self::MAX_OUTPUT + 1 - strlen( $output ) );
230            $too_big = strlen( $output ) > self::MAX_OUTPUT;
231        } while ( $status['running'] && ! $too_big && microtime( true ) < $deadline );
232
233        if ( $status['running'] ) {
234            self::stop( $process );
235        }
236        fclose( $pipes[1] ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- A process pipe, not a file.
237        proc_close( $process );
238
239        // proc_close() returns -1 once proc_get_status() has seen the exit.
240        if ( $too_big ) {
241            $this->log_error( 'output-too-large', $tool );
242        } elseif ( $status['running'] ) {
243            self::$broken_tools[ $name ] = true;
244            $this->log_error( 'timed-out', $tool );
245        } elseif ( 127 === $status['exitcode'] ) {
246            // Older PHP on Linux starts the child even when the program is missing, and it exits 127.
247            self::$broken_tools[ $name ] = true;
248            $this->log_error( 'could-not-start', $tool );
249        } elseif ( 0 !== $status['exitcode'] ) {
250            $this->log_error( 'tool-failed', $tool + array( 'exit_code' => $status['exitcode'] ) );
251        } else {
252            return $output;
253        }
254
255        return null;
256    }
257
258    /**
259     * Sends SIGINT so exiftool deletes its temp file, then SIGKILL after 1 second.
260     *
261     * @param resource $process The tool's process.
262     */
263    private static function stop( $process ) {
264        proc_terminate( $process, 2 );
265        $grace = microtime( true ) + 1;
266        while ( microtime( true ) < $grace ) {
267            usleep( 10000 );
268            if ( ! proc_get_status( $process )['running'] ) {
269                return;
270            }
271        }
272        proc_terminate( $process, 9 );
273    }
274
275    /**
276     * Whether a type is in SYNTHETIC_TYPES.
277     *
278     * @param mixed $digital_source_type The type a tool reported.
279     * @return bool
280     */
281    private static function is_synthetic( $digital_source_type ) {
282        return in_array( $digital_source_type, self::SYNTHETIC_TYPES, true );
283    }
284
285    /**
286     * Counts an error, and sends it to Logstash: stats don't reach Atomic.
287     *
288     * @param string $message The error, also used as the stat.
289     * @param array  $extra   Details for the Logstash entry.
290     */
291    private function log_error( $message, array $extra = array() ) {
292        // read() and write() call this from their catch blocks, so it must not throw.
293        try {
294            $this->bump_stat( $message );
295
296            $blog_id = get_current_blog_id();
297            if ( isset( self::$logged[ $blog_id ][ $message ] ) ) {
298                return;
299            }
300            self::$logged[ $blog_id ][ $message ] = true;
301
302            $extra = array( 'group' => $this->stats_group ) + $extra;
303            /**
304             * Filters whether to send an AI marker error to Logstash.
305             *
306             * @since $$next-version$$
307             *
308             * @param bool   $enabled Whether to send the entry. Default true.
309             * @param string $message The error.
310             * @param array  $extra   The entry's details.
311             */
312            if ( apply_filters( 'jetpack_wpcom_ai_marker_log_enabled', true, $message, $extra ) ) {
313                // The endpoint Atomic posts to only accepts features with an "atomic" prefix.
314                \Automattic\Jetpack\Jetpack_Mu_Wpcom::log2logstash( 'atomic_image_ai_marker', $message, $extra );
315            }
316        } catch ( Throwable $e ) {
317            unset( $e );
318        }
319    }
320
321    /**
322     * Bumps a stat in this caller's group.
323     *
324     * @param string $value The stat.
325     */
326    private function bump_stat( $value ) {
327        // The marker is optional, so a stats hook mustn't stop the save.
328        try {
329            do_action( 'jetpack_bump_stats_extras', $this->stats_group, $value );
330        } catch ( Throwable $e ) {
331            unset( $e );
332        }
333    }
334}