$dir, 'url' => trailingslashit( $uploads['baseurl'] ) . 'pinora', ); } /** * Public URL of a screenshot from the file name stored in meta. * * @param string $file File name. * @return string */ function pinora_screenshot_url( $file ) { return pinora_screenshot_dir()['url'] . '/' . rawurlencode( basename( $file ) ); } /** * Saves a screenshot sent as a data URL (JPEG or PNG). * * The content is checked to be a real image once written; anything else is * deleted straight away. * * @param int $id Note ID. * @param string $dataurl Encoded image, `data:image/jpeg;base64,…`. * @return bool */ function pinora_save_screenshot( $id, $dataurl ) { if ( ! preg_match( '#^data:image/(jpeg|png);base64,#', $dataurl, $m ) ) { return false; } // Decoding a data URL sent by the browser, not obfuscated code. $bytes = base64_decode( substr( $dataurl, strlen( $m[0] ) ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode if ( false === $bytes || strlen( $bytes ) > PINORA_SCREENSHOT_MAX ) { return false; } $dir = pinora_screenshot_dir(); $ext = 'png' === $m[1] ? 'png' : 'jpg'; $file = sprintf( 'note-%d-%s.%s', $id, strtolower( wp_generate_password( 12, false, false ) ), $ext ); $path = $dir['dir'] . '/' . $file; if ( false === file_put_contents( $path, $bytes ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents pinora_log( 'screenshot not written for note ' . $id ); return false; } $info = wp_getimagesize( $path ); if ( ! $info || ! in_array( $info['mime'], array( 'image/jpeg', 'image/png' ), true ) ) { wp_delete_file( $path ); return false; } update_post_meta( $id, '_pinora_screenshot', $file ); return true; } /** * Deletes the screenshot together with its note, whether the note goes from * the board or from the WordPress admin. * * @param int $id ID of the post being deleted. */ function pinora_delete_screenshot( $id ) { if ( PINORA_CPT !== get_post_type( $id ) ) { return; } $file = get_post_meta( $id, '_pinora_screenshot', true ); if ( $file ) { wp_delete_file( pinora_screenshot_dir()['dir'] . '/' . basename( $file ) ); } } add_action( 'before_delete_post', 'pinora_delete_screenshot' ); /** * Writes to the PHP error log when `WP_DEBUG` is on. Never blocking. * * @param string $message Message. */ function pinora_log( $message ) { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { error_log( '[pinora] ' . $message ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log } }