No Description

class.photon.php 49KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. <?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
  2. /**
  3. * Class for photon functionality.
  4. *
  5. * @package automattic/jetpack
  6. */
  7. use Automattic\Jetpack\Assets;
  8. /**
  9. * Class Jetpack_Photon
  10. */
  11. class Jetpack_Photon {
  12. /**
  13. * Singleton.
  14. *
  15. * @var null
  16. */
  17. private static $instance = null;
  18. /**
  19. * Allowed extensions.
  20. *
  21. * @var string[] Allowed extensions must match https://code.trac.wordpress.org/browser/photon/index.php#L41
  22. */
  23. protected static $extensions = array(
  24. 'gif',
  25. 'jpg',
  26. 'jpeg',
  27. 'png',
  28. 'webp', // Jetpack assumes Photon_OpenCV backend class is being used on the server. See link in docblock.
  29. );
  30. /**
  31. * Image sizes.
  32. *
  33. * Don't access this directly. Instead, use self::image_sizes() so it's actually populated with something.
  34. *
  35. * @var array Image sizes.
  36. */
  37. protected static $image_sizes = null;
  38. /**
  39. * Singleton implementation
  40. *
  41. * @return object
  42. */
  43. public static function instance() {
  44. if ( ! is_a( self::$instance, 'Jetpack_Photon' ) ) {
  45. self::$instance = new Jetpack_Photon();
  46. self::$instance->setup();
  47. }
  48. return self::$instance;
  49. }
  50. /**
  51. * Silence is golden.
  52. */
  53. private function __construct() {}
  54. /**
  55. * Register actions and filters, but only if basic Photon functions are available.
  56. * The basic functions are found in ./functions.photon.php.
  57. *
  58. * @uses add_action, add_filter
  59. * @return null
  60. */
  61. private function setup() {
  62. if ( ! function_exists( 'jetpack_photon_url' ) ) {
  63. return;
  64. }
  65. // Images in post content and galleries.
  66. add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 999999 );
  67. add_filter( 'get_post_galleries', array( __CLASS__, 'filter_the_galleries' ), 999999 );
  68. add_filter( 'widget_media_image_instance', array( __CLASS__, 'filter_the_image_widget' ), 999999 );
  69. // Core image retrieval.
  70. add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 10, 3 );
  71. add_filter( 'rest_request_before_callbacks', array( $this, 'should_rest_photon_image_downsize' ), 10, 3 );
  72. add_action( 'rest_after_insert_attachment', array( $this, 'should_rest_photon_image_downsize_insert_attachment' ), 10, 2 );
  73. add_filter( 'rest_request_after_callbacks', array( $this, 'cleanup_rest_photon_image_downsize' ) );
  74. // Responsive image srcset substitution.
  75. add_filter( 'wp_calculate_image_srcset', array( $this, 'filter_srcset_array' ), 10, 5 );
  76. add_filter( 'wp_calculate_image_sizes', array( $this, 'filter_sizes' ), 1, 2 ); // Early so themes can still easily filter.
  77. // Helpers for maniuplated images.
  78. add_action( 'wp_enqueue_scripts', array( $this, 'action_wp_enqueue_scripts' ), 9 );
  79. /**
  80. * Allow Photon to disable uploaded images resizing and use its own resize capabilities instead.
  81. *
  82. * @module photon
  83. *
  84. * @since 7.1.0
  85. *
  86. * @param bool false Should Photon enable noresize mode. Default to false.
  87. */
  88. if ( apply_filters( 'jetpack_photon_noresize_mode', false ) ) {
  89. $this->enable_noresize_mode();
  90. }
  91. }
  92. /**
  93. * Enables the noresize mode for Photon, allowing to avoid intermediate size files generation.
  94. */
  95. private function enable_noresize_mode() {
  96. jetpack_require_lib( 'class.jetpack-photon-image-sizes' );
  97. // The main objective of noresize mode is to disable additional resized image versions creation.
  98. // This filter handles removal of additional sizes.
  99. add_filter( 'intermediate_image_sizes_advanced', array( __CLASS__, 'filter_photon_noresize_intermediate_sizes' ) );
  100. // Load the noresize srcset solution on priority of 20, allowing other plugins to set sizes earlier.
  101. add_filter( 'wp_get_attachment_metadata', array( __CLASS__, 'filter_photon_norezise_maybe_inject_sizes' ), 20, 2 );
  102. // Photonize thumbnail URLs in the API response.
  103. add_filter( 'rest_api_thumbnail_size_urls', array( __CLASS__, 'filter_photon_noresize_thumbnail_urls' ) );
  104. // This allows to assign the Photon domain to images that normally use the home URL as base.
  105. add_filter( 'jetpack_photon_domain', array( __CLASS__, 'filter_photon_norezise_domain' ), 10, 2 );
  106. add_filter( 'the_content', array( __CLASS__, 'filter_content_add' ), 0 );
  107. // Jetpack hooks in at six nines (999999) so this filter does at seven.
  108. add_filter( 'the_content', array( __CLASS__, 'filter_content_remove' ), 9999999 );
  109. // Regular Photon operation mode filter doesn't run when is_admin(), so we need an additional filter.
  110. // This is temporary until Jetpack allows more easily running these filters for is_admin().
  111. if ( is_admin() ) {
  112. add_filter( 'image_downsize', array( $this, 'filter_image_downsize' ), 5, 3 );
  113. // Allows any image that gets passed to Photon to be resized via Photon.
  114. add_filter( 'jetpack_photon_admin_allow_image_downsize', '__return_true' );
  115. }
  116. }
  117. /**
  118. * This is our catch-all to strip dimensions from intermediate images in content.
  119. * Since this primarily only impacts post_content we do a little dance to add the filter early
  120. * to `the_content` and then remove it later on in the same hook.
  121. *
  122. * @param String $content the post content.
  123. * @return String the post content unchanged.
  124. */
  125. public static function filter_content_add( $content ) {
  126. add_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
  127. return $content;
  128. }
  129. /**
  130. * Removing the content filter that was set previously.
  131. *
  132. * @param String $content the post content.
  133. * @return String the post content unchanged.
  134. */
  135. public static function filter_content_remove( $content ) {
  136. remove_filter( 'jetpack_photon_pre_image_url', array( __CLASS__, 'strip_image_dimensions_maybe' ) );
  137. return $content;
  138. }
  139. /**
  140. * Short circuits the Photon filter to enable Photon processing for any URL.
  141. *
  142. * @param String $photon_url a proposed Photon URL for the media file.
  143. *
  144. * @return String an URL to be used for the media file.
  145. */
  146. public static function filter_photon_norezise_domain( $photon_url ) {
  147. return $photon_url;
  148. }
  149. /**
  150. * Disables intermediate sizes to disallow resizing.
  151. *
  152. * @return array Empty array.
  153. */
  154. public static function filter_photon_noresize_intermediate_sizes() {
  155. return array();
  156. }
  157. /**
  158. * Filter thumbnail URLS to not generate.
  159. *
  160. * @param array $sizes Image sizes.
  161. *
  162. * @return mixed
  163. */
  164. public static function filter_photon_noresize_thumbnail_urls( $sizes ) {
  165. foreach ( $sizes as $size => $url ) {
  166. $parts = explode( '?', $url );
  167. $arguments = isset( $parts[1] ) ? $parts[1] : array();
  168. $sizes[ $size ] = jetpack_photon_url( $url, wp_parse_args( $arguments ) );
  169. }
  170. return $sizes;
  171. }
  172. /**
  173. * Inject image sizes to attachment metadata.
  174. *
  175. * @param array $data Attachment metadata.
  176. * @param int $attachment_id Attachment's post ID.
  177. *
  178. * @return array Attachment metadata.
  179. */
  180. public static function filter_photon_norezise_maybe_inject_sizes( $data, $attachment_id ) {
  181. // Can't do much if data is empty.
  182. if ( empty( $data ) ) {
  183. return $data;
  184. }
  185. $sizes_already_exist = (
  186. true === is_array( $data )
  187. && true === array_key_exists( 'sizes', $data )
  188. && true === is_array( $data['sizes'] )
  189. && false === empty( $data['sizes'] )
  190. );
  191. if ( $sizes_already_exist ) {
  192. return $data;
  193. }
  194. // Missing some critical data we need to determine sizes, not processing.
  195. if ( ! isset( $data['file'] )
  196. || ! isset( $data['width'] )
  197. || ! isset( $data['height'] )
  198. ) {
  199. return $data;
  200. }
  201. $mime_type = get_post_mime_type( $attachment_id );
  202. $attachment_is_image = preg_match( '!^image/!', $mime_type );
  203. if ( 1 === $attachment_is_image ) {
  204. $image_sizes = new Jetpack_Photon_ImageSizes( $attachment_id, $data );
  205. $data['sizes'] = $image_sizes->generate_sizes_meta();
  206. }
  207. return $data;
  208. }
  209. /**
  210. * Inject image sizes to Jetpack REST API responses. This wraps the filter_photon_norezise_maybe_inject_sizes function.
  211. *
  212. * @param array $sizes Attachment sizes data.
  213. * @param int $attachment_id Attachment's post ID.
  214. *
  215. * @return array Attachment sizes array.
  216. */
  217. public static function filter_photon_norezise_maybe_inject_sizes_api( $sizes, $attachment_id ) {
  218. return self::filter_photon_norezise_maybe_inject_sizes( wp_get_attachment_metadata( $attachment_id ), $attachment_id );
  219. }
  220. /**
  221. * * IN-CONTENT IMAGE MANIPULATION FUNCTIONS
  222. **/
  223. /**
  224. * Match all images and any relevant <a> tags in a block of HTML.
  225. *
  226. * @param string $content Some HTML.
  227. * @return array An array of $images matches, where $images[0] is
  228. * an array of full matches, and the link_url, img_tag,
  229. * and img_url keys are arrays of those matches.
  230. */
  231. public static function parse_images_from_html( $content ) {
  232. $images = array();
  233. if ( preg_match_all( '#(?:<a[^>]+?href=["|\'](?P<link_url>[^\s]+?)["|\'][^>]*?>\s*)?(?P<img_tag><(?:img|amp-img|amp-anim)[^>]*?\s+?src=["|\'](?P<img_url>[^\s]+?)["|\'].*?>){1}(?:\s*</a>)?#is', $content, $images ) ) {
  234. foreach ( $images as $key => $unused ) {
  235. // Simplify the output as much as possible, mostly for confirming test results.
  236. if ( is_numeric( $key ) && $key > 0 ) {
  237. unset( $images[ $key ] );
  238. }
  239. }
  240. return $images;
  241. }
  242. return array();
  243. }
  244. /**
  245. * Try to determine height and width from strings WP appends to resized image filenames.
  246. *
  247. * @param string $src The image URL.
  248. * @return array An array consisting of width and height.
  249. */
  250. public static function parse_dimensions_from_filename( $src ) {
  251. $width_height_string = array();
  252. if ( preg_match( '#-(\d+)x(\d+)\.(?:' . implode( '|', self::$extensions ) . '){1}$#i', $src, $width_height_string ) ) {
  253. $width = (int) $width_height_string[1];
  254. $height = (int) $width_height_string[2];
  255. if ( $width && $height ) {
  256. return array( $width, $height );
  257. }
  258. }
  259. return array( false, false );
  260. }
  261. /**
  262. * Identify images in post content, and if images are local (uploaded to the current site), pass through Photon.
  263. *
  264. * @param string $content The content.
  265. *
  266. * @uses self::validate_image_url, apply_filters, jetpack_photon_url, esc_url
  267. * @filter the_content
  268. *
  269. * @return string
  270. */
  271. public static function filter_the_content( $content ) {
  272. $images = self::parse_images_from_html( $content );
  273. if ( ! empty( $images ) ) {
  274. $content_width = Jetpack::get_content_width();
  275. $image_sizes = self::image_sizes();
  276. $upload_dir = wp_get_upload_dir();
  277. foreach ( $images[0] as $index => $tag ) {
  278. // Default to resize, though fit may be used in certain cases where a dimension cannot be ascertained.
  279. $transform = 'resize';
  280. // Start with a clean attachment ID each time.
  281. $attachment_id = false;
  282. // Flag if we need to munge a fullsize URL.
  283. $fullsize_url = false;
  284. // Identify image source.
  285. $src_orig = $images['img_url'][ $index ];
  286. $src = $src_orig;
  287. /**
  288. * Allow specific images to be skipped by Photon.
  289. *
  290. * @module photon
  291. *
  292. * @since 2.0.3
  293. *
  294. * @param bool false Should Photon ignore this image. Default to false.
  295. * @param string $src Image URL.
  296. * @param string $tag Image Tag (Image HTML output).
  297. */
  298. if ( apply_filters( 'jetpack_photon_skip_image', false, $src, $tag ) ) {
  299. continue;
  300. }
  301. // Support Automattic's Lazy Load plugin.
  302. // Can't modify $tag yet as we need unadulterated version later.
  303. if ( preg_match( '#data-lazy-src=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
  304. $placeholder_src_orig = $src;
  305. $placeholder_src = $placeholder_src_orig;
  306. $src_orig = $lazy_load_src[1];
  307. $src = $src_orig;
  308. } elseif ( preg_match( '#data-lazy-original=["|\'](.+?)["|\']#i', $images['img_tag'][ $index ], $lazy_load_src ) ) {
  309. $placeholder_src_orig = $src;
  310. $placeholder_src = $placeholder_src_orig;
  311. $src_orig = $lazy_load_src[1];
  312. $src = $src_orig;
  313. }
  314. // Check if image URL should be used with Photon.
  315. if ( self::validate_image_url( $src ) ) {
  316. // Find the width and height attributes.
  317. $width = false;
  318. $height = false;
  319. // First, check the image tag. Note we only check for pixel sizes now; HTML4 percentages have never been correctly
  320. // supported, so we stopped pretending to support them in JP 9.1.0.
  321. if ( preg_match( '#[\s|"|\']width=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $width_string ) ) {
  322. $width = false === strpos( $width_string[1], '%' ) ? $width_string[1] : false;
  323. }
  324. if ( preg_match( '#[\s|"|\']height=["|\']?([\d%]+)["|\']?#i', $images['img_tag'][ $index ], $height_string ) ) {
  325. $height = false === strpos( $height_string[1], '%' ) ? $height_string[1] : false;
  326. }
  327. // Detect WP registered image size from HTML class.
  328. if ( preg_match( '#class=["|\']?[^"\']*size-([^"\'\s]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $size ) ) {
  329. $size = array_pop( $size );
  330. if ( false === $width && false === $height && 'full' !== $size && array_key_exists( $size, $image_sizes ) ) {
  331. $width = (int) $image_sizes[ $size ]['width'];
  332. $height = (int) $image_sizes[ $size ]['height'];
  333. $transform = $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
  334. }
  335. } else {
  336. unset( $size );
  337. }
  338. // WP Attachment ID, if uploaded to this site.
  339. if (
  340. preg_match( '#class=["|\']?[^"\']*wp-image-([\d]+)[^"\']*["|\']?#i', $images['img_tag'][ $index ], $attachment_id ) &&
  341. 0 === strpos( $src, $upload_dir['baseurl'] ) &&
  342. /**
  343. * Filter whether an image using an attachment ID in its class has to be uploaded to the local site to go through Photon.
  344. *
  345. * @module photon
  346. *
  347. * @since 2.0.3
  348. *
  349. * @param bool false Was the image uploaded to the local site. Default to false.
  350. * @param array $args {
  351. * Array of image details.
  352. *
  353. * @type $src Image URL.
  354. * @type tag Image tag (Image HTML output).
  355. * @type $images Array of information about the image.
  356. * @type $index Image index.
  357. * }
  358. */
  359. apply_filters( 'jetpack_photon_image_is_local', false, compact( 'src', 'tag', 'images', 'index' ) )
  360. ) {
  361. $attachment_id = (int) array_pop( $attachment_id );
  362. if ( $attachment_id ) {
  363. $attachment = get_post( $attachment_id );
  364. // Basic check on returned post object.
  365. if ( is_object( $attachment ) && ! is_wp_error( $attachment ) && 'attachment' === $attachment->post_type ) {
  366. $src_per_wp = wp_get_attachment_image_src( $attachment_id, isset( $size ) ? $size : 'full' );
  367. if ( self::validate_image_url( $src_per_wp[0] ) ) {
  368. $src = $src_per_wp[0];
  369. $fullsize_url = true;
  370. // Prevent image distortion if a detected dimension exceeds the image's natural dimensions.
  371. if ( ( false !== $width && $width > $src_per_wp[1] ) || ( false !== $height && $height > $src_per_wp[2] ) ) {
  372. $width = false === $width ? false : min( $width, $src_per_wp[1] );
  373. $height = false === $height ? false : min( $height, $src_per_wp[2] );
  374. }
  375. // If no width and height are found, max out at source image's natural dimensions.
  376. // Otherwise, respect registered image sizes' cropping setting.
  377. if ( false === $width && false === $height ) {
  378. $width = $src_per_wp[1];
  379. $height = $src_per_wp[2];
  380. $transform = 'fit';
  381. } elseif ( isset( $size ) && array_key_exists( $size, $image_sizes ) && isset( $image_sizes[ $size ]['crop'] ) ) {
  382. $transform = (bool) $image_sizes[ $size ]['crop'] ? 'resize' : 'fit';
  383. }
  384. }
  385. } else {
  386. unset( $attachment_id );
  387. unset( $attachment );
  388. }
  389. }
  390. }
  391. // If image tag lacks width and height arguments, try to determine from strings WP appends to resized image filenames.
  392. if ( false === $width && false === $height ) {
  393. list( $width, $height ) = self::parse_dimensions_from_filename( $src );
  394. }
  395. $width_orig = $width;
  396. $height_orig = $height;
  397. $transform_orig = $transform;
  398. // If width is available, constrain to $content_width.
  399. if ( false !== $width && is_numeric( $content_width ) && $width > $content_width ) {
  400. if ( false !== $height ) {
  401. $height = round( ( $content_width * $height ) / $width );
  402. }
  403. $width = $content_width;
  404. }
  405. // Set a width if none is found and $content_width is available.
  406. // If width is set in this manner and height is available, use `fit` instead of `resize` to prevent skewing.
  407. if ( false === $width && is_numeric( $content_width ) ) {
  408. $width = (int) $content_width;
  409. if ( false !== $height ) {
  410. $transform = 'fit';
  411. }
  412. }
  413. // Detect if image source is for a custom-cropped thumbnail and prevent further URL manipulation.
  414. if ( ! $fullsize_url && preg_match_all( '#-e[a-z0-9]+(-\d+x\d+)?\.(' . implode( '|', self::$extensions ) . '){1}$#i', basename( $src ), $filename ) ) {
  415. $fullsize_url = true;
  416. }
  417. // Build URL, first maybe removing WP's resized string so we pass the original image to Photon.
  418. if ( ! $fullsize_url && 0 === strpos( $src, $upload_dir['baseurl'] ) ) {
  419. $src = self::strip_image_dimensions_maybe( $src );
  420. }
  421. // Build array of Photon args and expose to filter before passing to Photon URL function.
  422. $args = array();
  423. if ( false !== $width && false !== $height ) {
  424. $args[ $transform ] = $width . ',' . $height;
  425. } elseif ( false !== $width ) {
  426. $args['w'] = $width;
  427. } elseif ( false !== $height ) {
  428. $args['h'] = $height;
  429. }
  430. /**
  431. * Filter the array of Photon arguments added to an image when it goes through Photon.
  432. * By default, only includes width and height values.
  433. *
  434. * @see https://developer.wordpress.com/docs/photon/api/
  435. *
  436. * @module photon
  437. *
  438. * @since 2.0.0
  439. *
  440. * @param array $args Array of Photon Arguments.
  441. * @param array $details {
  442. * Array of image details.
  443. *
  444. * @type string $tag Image tag (Image HTML output).
  445. * @type string $src Image URL.
  446. * @type string $src_orig Original Image URL.
  447. * @type int|false $width Image width.
  448. * @type int|false $height Image height.
  449. * @type int|false $width_orig Original image width before constrained by content_width.
  450. * @type int|false $height_orig Original Image height before constrained by content_width.
  451. * @type string $transform Transform.
  452. * @type string $transform_orig Original transform before constrained by content_width.
  453. * }
  454. */
  455. $args = apply_filters( 'jetpack_photon_post_image_args', $args, compact( 'tag', 'src', 'src_orig', 'width', 'height', 'width_orig', 'height_orig', 'transform', 'transform_orig' ) );
  456. $photon_url = jetpack_photon_url( $src, $args );
  457. // Modify image tag if Photon function provides a URL
  458. // Ensure changes are only applied to the current image by copying and modifying the matched tag, then replacing the entire tag with our modified version.
  459. if ( $src !== $photon_url ) {
  460. $new_tag = $tag;
  461. // If present, replace the link href with a Photoned URL for the full-size image.
  462. if ( ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
  463. $new_tag = preg_replace( '#(href=["|\'])' . preg_quote( $images['link_url'][ $index ], '#' ) . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $new_tag, 1 );
  464. }
  465. // Supplant the original source value with our Photon URL.
  466. $photon_url = esc_url( $photon_url );
  467. $new_tag = str_replace( $src_orig, $photon_url, $new_tag );
  468. // If Lazy Load is in use, pass placeholder image through Photon.
  469. if ( isset( $placeholder_src ) && self::validate_image_url( $placeholder_src ) ) {
  470. $placeholder_src = jetpack_photon_url( $placeholder_src );
  471. if ( $placeholder_src !== $placeholder_src_orig ) {
  472. $new_tag = str_replace( $placeholder_src_orig, esc_url( $placeholder_src ), $new_tag );
  473. }
  474. unset( $placeholder_src );
  475. }
  476. // If we are not transforming the image with resize, fit, or letterbox (lb), then we should remove
  477. // the width and height arguments (including HTML4 percentages) from the image to prevent distortion.
  478. // Even if $args['w'] and $args['h'] are present, Photon does not crop to those dimensions. Instead,
  479. // it appears to favor height.
  480. //
  481. // If we are transforming the image via one of those methods, let's update the width and height attributes.
  482. if ( empty( $args['resize'] ) && empty( $args['fit'] ) && empty( $args['lb'] ) ) {
  483. $new_tag = preg_replace( '#(?<=\s)(width|height)=["|\']?[\d%]+["|\']?\s?#i', '', $new_tag );
  484. } else {
  485. $resize_args = isset( $args['resize'] ) ? $args['resize'] : false;
  486. if ( false === $resize_args ) {
  487. $resize_args = ( ! $resize_args && isset( $args['fit'] ) )
  488. ? $args['fit']
  489. : false;
  490. }
  491. if ( false === $resize_args ) {
  492. $resize_args = ( ! $resize_args && isset( $args['lb'] ) )
  493. ? $args['lb']
  494. : false;
  495. }
  496. $resize_args = array_map( 'trim', explode( ',', $resize_args ) );
  497. // (?<=\s) - Ensure width or height attribute is preceded by a space
  498. // (width=["|\']?) - Matches, and captures, width=, width=", or width='
  499. // [\d%]+ - Matches 1 or more digits or percent signs
  500. // (["|\']?) - Matches, and captures, ", ', or empty string
  501. // \s - Ensures there's a space after the attribute
  502. $new_tag = preg_replace( '#(?<=\s)(width=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[0] ), $new_tag );
  503. $new_tag = preg_replace( '#(?<=\s)(height=["|\']?)[\d%]+(["|\']?)\s?#i', sprintf( '${1}%d${2} ', $resize_args[1] ), $new_tag );
  504. }
  505. // Tag an image for dimension checking.
  506. if ( ! self::is_amp_endpoint() ) {
  507. $new_tag = preg_replace( '#(\s?/)?>(\s*</a>)?$#i', ' data-recalc-dims="1"\1>\2', $new_tag );
  508. }
  509. // Replace original tag with modified version.
  510. $content = str_replace( $tag, $new_tag, $content );
  511. }
  512. } elseif ( preg_match( '#^http(s)?://i[\d]{1}.wp.com#', $src ) && ! empty( $images['link_url'][ $index ] ) && self::validate_image_url( $images['link_url'][ $index ] ) ) {
  513. $new_tag = preg_replace( '#(href=["|\'])' . preg_quote( $images['link_url'][ $index ], '#' ) . '(["|\'])#i', '\1' . jetpack_photon_url( $images['link_url'][ $index ] ) . '\2', $tag, 1 );
  514. $content = str_replace( $tag, $new_tag, $content );
  515. }
  516. }
  517. }
  518. return $content;
  519. }
  520. /**
  521. * Filter Core galleries
  522. *
  523. * @param array $galleries Gallery array.
  524. *
  525. * @return array
  526. */
  527. public static function filter_the_galleries( $galleries ) {
  528. if ( empty( $galleries ) || ! is_array( $galleries ) ) {
  529. return $galleries;
  530. }
  531. // Pass by reference, so we can modify them in place.
  532. foreach ( $galleries as &$this_gallery ) {
  533. if ( is_string( $this_gallery ) ) {
  534. $this_gallery = self::filter_the_content( $this_gallery );
  535. }
  536. }
  537. unset( $this_gallery ); // break the reference.
  538. return $galleries;
  539. }
  540. /**
  541. * Runs the image widget through photon.
  542. *
  543. * @param array $instance Image widget instance data.
  544. * @return array
  545. */
  546. public static function filter_the_image_widget( $instance ) {
  547. if ( Jetpack::is_module_active( 'photon' ) && ! $instance['attachment_id'] && $instance['url'] ) {
  548. jetpack_photon_url(
  549. $instance['url'],
  550. array(
  551. 'w' => $instance['width'],
  552. 'h' => $instance['height'],
  553. )
  554. );
  555. }
  556. return $instance;
  557. }
  558. /**
  559. * * CORE IMAGE RETRIEVAL
  560. **/
  561. /**
  562. * Filter post thumbnail image retrieval, passing images through Photon
  563. *
  564. * @param string|bool $image Image URL.
  565. * @param int $attachment_id Attachment ID.
  566. * @param string|array $size Declared size or a size array.
  567. * @uses is_admin, apply_filters, wp_get_attachment_url, self::validate_image_url, this::image_sizes, jetpack_photon_url
  568. * @filter image_downsize
  569. * @return string|bool
  570. */
  571. public function filter_image_downsize( $image, $attachment_id, $size ) {
  572. // Don't foul up the admin side of things, unless a plugin wants to.
  573. if ( is_admin() &&
  574. /**
  575. * Provide plugins a way of running Photon for images in the WordPress Dashboard (wp-admin).
  576. *
  577. * Note: enabling this will result in Photon URLs added to your post content, which could make migrations across domains (and off Photon) a bit more challenging.
  578. *
  579. * @module photon
  580. *
  581. * @since 4.8.0
  582. *
  583. * @param bool false Stop Photon from being run on the Dashboard. Default to false.
  584. * @param array $args {
  585. * Array of image details.
  586. *
  587. * @type $image Image URL.
  588. * @type $attachment_id Attachment ID of the image.
  589. * @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
  590. * }
  591. */
  592. false === apply_filters( 'jetpack_photon_admin_allow_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) )
  593. ) {
  594. return $image;
  595. }
  596. /**
  597. * Provide plugins a way of preventing Photon from being applied to images retrieved from WordPress Core.
  598. *
  599. * @module photon
  600. *
  601. * @since 2.0.0
  602. *
  603. * @param bool false Stop Photon from being applied to the image. Default to false.
  604. * @param array $args {
  605. * Array of image details.
  606. *
  607. * @type $image Image URL.
  608. * @type $attachment_id Attachment ID of the image.
  609. * @type $size Image size. Can be a string (name of the image size, e.g. full) or an array of width and height.
  610. * }
  611. */
  612. if ( apply_filters( 'jetpack_photon_override_image_downsize', false, compact( 'image', 'attachment_id', 'size' ) ) ) {
  613. return $image;
  614. }
  615. // Get the image URL and proceed with Photon-ification if successful.
  616. $image_url = wp_get_attachment_url( $attachment_id );
  617. // Set this to true later when we know we have size meta.
  618. $has_size_meta = false;
  619. if ( $image_url ) {
  620. // Check if image URL should be used with Photon.
  621. if ( ! self::validate_image_url( $image_url ) ) {
  622. return $image;
  623. }
  624. $intermediate = true; // For the fourth array item returned by the image_downsize filter.
  625. // If an image is requested with a size known to WordPress, use that size's settings with Photon.
  626. // WP states that `add_image_size()` should use a string for the name, but doesn't enforce that.
  627. // Due to differences in how Core and Photon check for the registered image size, we check both types.
  628. if ( ( is_string( $size ) || is_int( $size ) ) && array_key_exists( $size, self::image_sizes() ) ) {
  629. $image_args = self::image_sizes();
  630. $image_args = $image_args[ $size ];
  631. $photon_args = array();
  632. $image_meta = image_get_intermediate_size( $attachment_id, $size );
  633. // 'full' is a special case: We need consistent data regardless of the requested size.
  634. if ( 'full' === $size ) {
  635. $image_meta = wp_get_attachment_metadata( $attachment_id );
  636. $intermediate = false;
  637. } elseif ( ! $image_meta ) {
  638. // If we still don't have any image meta at this point, it's probably from a custom thumbnail size
  639. // for an image that was uploaded before the custom image was added to the theme. Try to determine the size manually.
  640. $image_meta = wp_get_attachment_metadata( $attachment_id );
  641. if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
  642. $image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $image_args['width'], $image_args['height'], $image_args['crop'] );
  643. if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
  644. $image_meta['width'] = $image_resized[6];
  645. $image_meta['height'] = $image_resized[7];
  646. }
  647. }
  648. }
  649. if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
  650. $image_args['width'] = (int) $image_meta['width'];
  651. $image_args['height'] = (int) $image_meta['height'];
  652. list( $image_args['width'], $image_args['height'] ) = image_constrain_size_for_editor( $image_args['width'], $image_args['height'], $size, 'display' );
  653. $has_size_meta = true;
  654. }
  655. // Expose determined arguments to a filter before passing to Photon.
  656. $transform = $image_args['crop'] ? 'resize' : 'fit';
  657. // Check specified image dimensions and account for possible zero values; photon fails to resize if a dimension is zero.
  658. if ( 0 === $image_args['width'] || 0 === $image_args['height'] ) {
  659. if ( 0 === $image_args['width'] && 0 < $image_args['height'] ) {
  660. $photon_args['h'] = $image_args['height'];
  661. } elseif ( 0 === $image_args['height'] && 0 < $image_args['width'] ) {
  662. $photon_args['w'] = $image_args['width'];
  663. }
  664. } else {
  665. $image_meta = wp_get_attachment_metadata( $attachment_id );
  666. if ( ( 'resize' === $transform ) && $image_meta ) {
  667. if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
  668. // Lets make sure that we don't upscale images since wp never upscales them as well.
  669. $smaller_width = ( ( $image_meta['width'] < $image_args['width'] ) ? $image_meta['width'] : $image_args['width'] );
  670. $smaller_height = ( ( $image_meta['height'] < $image_args['height'] ) ? $image_meta['height'] : $image_args['height'] );
  671. $photon_args[ $transform ] = $smaller_width . ',' . $smaller_height;
  672. }
  673. } else {
  674. $photon_args[ $transform ] = $image_args['width'] . ',' . $image_args['height'];
  675. }
  676. }
  677. /**
  678. * Filter the Photon Arguments added to an image when going through Photon, when that image size is a string.
  679. * Image size will be a string (e.g. "full", "medium") when it is known to WordPress.
  680. *
  681. * @module photon
  682. *
  683. * @since 2.0.0
  684. *
  685. * @param array $photon_args Array of Photon arguments.
  686. * @param array $args {
  687. * Array of image details.
  688. *
  689. * @type array $image_args Array of Image arguments (width, height, crop).
  690. * @type string $image_url Image URL.
  691. * @type int $attachment_id Attachment ID of the image.
  692. * @type string|int $size Image size. Can be a string (name of the image size, e.g. full) or an integer.
  693. * @type string $transform Value can be resize or fit.
  694. * @see https://developer.wordpress.com/docs/photon/api
  695. * }
  696. */
  697. $photon_args = apply_filters( 'jetpack_photon_image_downsize_string', $photon_args, compact( 'image_args', 'image_url', 'attachment_id', 'size', 'transform' ) );
  698. // Generate Photon URL.
  699. $image = array(
  700. jetpack_photon_url( $image_url, $photon_args ),
  701. $has_size_meta ? $image_args['width'] : false,
  702. $has_size_meta ? $image_args['height'] : false,
  703. $intermediate,
  704. );
  705. } elseif ( is_array( $size ) ) {
  706. // Pull width and height values from the provided array, if possible.
  707. $width = isset( $size[0] ) ? (int) $size[0] : false;
  708. $height = isset( $size[1] ) ? (int) $size[1] : false;
  709. // Don't bother if necessary parameters aren't passed.
  710. if ( ! $width || ! $height ) {
  711. return $image;
  712. }
  713. $image_meta = wp_get_attachment_metadata( $attachment_id );
  714. if ( isset( $image_meta['width'], $image_meta['height'] ) ) {
  715. $image_resized = image_resize_dimensions( $image_meta['width'], $image_meta['height'], $width, $height );
  716. if ( $image_resized ) { // This could be false when the requested image size is larger than the full-size image.
  717. $width = $image_resized[6];
  718. $height = $image_resized[7];
  719. } else {
  720. $width = $image_meta['width'];
  721. $height = $image_meta['height'];
  722. }
  723. $has_size_meta = true;
  724. }
  725. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  726. // Expose arguments to a filter before passing to Photon.
  727. $photon_args = array(
  728. 'fit' => $width . ',' . $height,
  729. );
  730. /**
  731. * Filter the Photon Arguments added to an image when going through Photon,
  732. * when the image size is an array of height and width values.
  733. *
  734. * @module photon
  735. *
  736. * @since 2.0.0
  737. *
  738. * @param array $photon_args Array of Photon arguments.
  739. * @param array $args {
  740. * Array of image details.
  741. *
  742. * @type $width Image width.
  743. * @type height Image height.
  744. * @type $image_url Image URL.
  745. * @type $attachment_id Attachment ID of the image.
  746. * }
  747. */
  748. $photon_args = apply_filters( 'jetpack_photon_image_downsize_array', $photon_args, compact( 'width', 'height', 'image_url', 'attachment_id' ) );
  749. // Generate Photon URL.
  750. $image = array(
  751. jetpack_photon_url( $image_url, $photon_args ),
  752. $has_size_meta ? $width : false,
  753. $has_size_meta ? $height : false,
  754. $intermediate,
  755. );
  756. }
  757. }
  758. return $image;
  759. }
  760. /**
  761. * Filters an array of image `srcset` values, replacing each URL with its Photon equivalent.
  762. *
  763. * @since 3.8.0
  764. * @since 4.0.4 Added automatically additional sizes beyond declared image sizes.
  765. *
  766. * @param array $sources An array of image urls and widths.
  767. * @param array $size_array The size array for srcset.
  768. * @param array $image_src The image srcs.
  769. * @param array $image_meta The image meta.
  770. * @param int $attachment_id Attachment ID.
  771. *
  772. * @uses self::validate_image_url, jetpack_photon_url, Jetpack_Photon::parse_from_filename
  773. * @uses Jetpack_Photon::strip_image_dimensions_maybe, Jetpack::get_content_width
  774. *
  775. * @return array An array of Photon image urls and widths.
  776. */
  777. public function filter_srcset_array( $sources = array(), $size_array = array(), $image_src = array(), $image_meta = array(), $attachment_id = 0 ) {
  778. if ( ! is_array( $sources ) ) {
  779. return $sources;
  780. }
  781. $upload_dir = wp_get_upload_dir();
  782. foreach ( $sources as $i => $source ) {
  783. if ( ! self::validate_image_url( $source['url'] ) ) {
  784. continue;
  785. }
  786. /** This filter is already documented in class.photon.php */
  787. if ( apply_filters( 'jetpack_photon_skip_image', false, $source['url'], $source ) ) {
  788. continue;
  789. }
  790. $url = $source['url'];
  791. list( $width, $height ) = self::parse_dimensions_from_filename( $url );
  792. // It's quicker to get the full size with the data we have already, if available.
  793. if ( ! empty( $attachment_id ) ) {
  794. $url = wp_get_attachment_url( $attachment_id );
  795. } else {
  796. $url = self::strip_image_dimensions_maybe( $url );
  797. }
  798. $args = array();
  799. if ( 'w' === $source['descriptor'] ) {
  800. if ( $height && ( (int) $source['value'] === $width ) ) {
  801. $args['resize'] = $width . ',' . $height;
  802. } else {
  803. $args['w'] = $source['value'];
  804. }
  805. }
  806. $sources[ $i ]['url'] = jetpack_photon_url( $url, $args );
  807. }
  808. /**
  809. * At this point, $sources is the original srcset with Photonized URLs.
  810. * Now, we're going to construct additional sizes based on multiples of the content_width.
  811. * This will reduce the gap between the largest defined size and the original image.
  812. */
  813. /**
  814. * Filter the multiplier Photon uses to create new srcset items.
  815. * Return false to short-circuit and bypass auto-generation.
  816. *
  817. * @module photon
  818. *
  819. * @since 4.0.4
  820. *
  821. * @param array|bool $multipliers Array of multipliers to use or false to bypass.
  822. */
  823. $multipliers = apply_filters( 'jetpack_photon_srcset_multipliers', array( 2, 3 ) );
  824. $url = trailingslashit( $upload_dir['baseurl'] ) . $image_meta['file'];
  825. if (
  826. /** Short-circuit via jetpack_photon_srcset_multipliers filter. */
  827. is_array( $multipliers )
  828. /** This filter is already documented in class.photon.php */
  829. && ! apply_filters( 'jetpack_photon_skip_image', false, $url, null )
  830. /** Verify basic meta is intact. */
  831. && isset( $image_meta['width'] ) && isset( $image_meta['height'] ) && isset( $image_meta['file'] )
  832. /** Verify we have the requested width/height. */
  833. && isset( $size_array[0] ) && isset( $size_array[1] )
  834. ) {
  835. $fullwidth = $image_meta['width'];
  836. $fullheight = $image_meta['height'];
  837. $reqwidth = $size_array[0];
  838. $reqheight = $size_array[1];
  839. $constrained_size = wp_constrain_dimensions( $fullwidth, $fullheight, $reqwidth );
  840. $expected_size = array( $reqwidth, $reqheight );
  841. if ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 ) {
  842. $crop = 'soft';
  843. $base = Jetpack::get_content_width() ? Jetpack::get_content_width() : 1000; // Provide a default width if none set by the theme.
  844. } else {
  845. $crop = 'hard';
  846. $base = $reqwidth;
  847. }
  848. $currentwidths = array_keys( $sources );
  849. $newsources = null;
  850. foreach ( $multipliers as $multiplier ) {
  851. $newwidth = $base * $multiplier;
  852. foreach ( $currentwidths as $currentwidth ) {
  853. // If a new width would be within 100 pixes of an existing one or larger than the full size image, skip.
  854. if ( abs( $currentwidth - $newwidth ) < 50 || ( $newwidth > $fullwidth ) ) {
  855. continue 2; // Bump out back to the $multipliers as $multiplier.
  856. }
  857. } //end foreach ( $currentwidths as $currentwidth ){
  858. if ( 'soft' === $crop ) {
  859. $args = array(
  860. 'w' => $newwidth,
  861. );
  862. } else { // hard crop, e.g. add_image_size( 'example', 200, 200, true ).
  863. $args = array(
  864. 'zoom' => $multiplier,
  865. 'resize' => $reqwidth . ',' . $reqheight,
  866. );
  867. }
  868. $newsources[ $newwidth ] = array(
  869. 'url' => jetpack_photon_url( $url, $args ),
  870. 'descriptor' => 'w',
  871. 'value' => $newwidth,
  872. );
  873. } //end foreach ( $multipliers as $multiplier )
  874. if ( is_array( $newsources ) ) {
  875. $sources = array_replace( $sources, $newsources );
  876. }
  877. } //end if isset( $image_meta['width'] ) && isset( $image_meta['file'] ) )
  878. return $sources;
  879. }
  880. /**
  881. * Filters an array of image `sizes` values, using $content_width instead of image's full size.
  882. *
  883. * @since 4.0.4
  884. * @since 4.1.0 Returns early for images not within the_content.
  885. * @param array $sizes An array of media query breakpoints.
  886. * @param array $size Width and height of the image.
  887. * @uses Jetpack::get_content_width
  888. * @return array An array of media query breakpoints.
  889. */
  890. public function filter_sizes( $sizes, $size ) {
  891. if ( ! doing_filter( 'the_content' ) ) {
  892. return $sizes;
  893. }
  894. $content_width = Jetpack::get_content_width();
  895. if ( ! $content_width ) {
  896. $content_width = 1000;
  897. }
  898. if ( ( is_array( $size ) && $size[0] < $content_width ) ) {
  899. return $sizes;
  900. }
  901. return sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $content_width );
  902. }
  903. /**
  904. * * GENERAL FUNCTIONS
  905. **/
  906. /**
  907. * Ensure image URL is valid for Photon.
  908. * Though Photon functions address some of the URL issues, we should avoid unnecessary processing if we know early on that the image isn't supported.
  909. *
  910. * @param string $url Image URL.
  911. * @uses wp_parse_args
  912. * @return bool
  913. */
  914. protected static function validate_image_url( $url ) {
  915. $parsed_url = wp_parse_url( $url );
  916. if ( ! $parsed_url ) {
  917. return false;
  918. }
  919. // Parse URL and ensure needed keys exist, since the array returned by `wp_parse_url` only includes the URL components it finds.
  920. $url_info = wp_parse_args(
  921. $parsed_url,
  922. array(
  923. 'scheme' => null,
  924. 'host' => null,
  925. 'port' => null,
  926. 'path' => null,
  927. )
  928. );
  929. // Bail if scheme isn't http or port is set that isn't port 80.
  930. if (
  931. ( 'http' !== $url_info['scheme'] || ! in_array( $url_info['port'], array( 80, null ), true ) ) &&
  932. /**
  933. * Allow Photon to fetch images that are served via HTTPS.
  934. *
  935. * @module photon
  936. *
  937. * @since 2.4.0
  938. * @since 3.9.0 Default to false.
  939. *
  940. * @param bool $reject_https Should Photon ignore images using the HTTPS scheme. Default to false.
  941. */
  942. apply_filters( 'jetpack_photon_reject_https', false )
  943. ) {
  944. return false;
  945. }
  946. // Bail if no host is found.
  947. if ( is_null( $url_info['host'] ) ) {
  948. return false;
  949. }
  950. // Bail if the image already went through Photon.
  951. if ( preg_match( '#^i[\d]{1}.wp.com$#i', $url_info['host'] ) ) {
  952. return false;
  953. }
  954. // Bail if no path is found.
  955. if ( is_null( $url_info['path'] ) ) {
  956. return false;
  957. }
  958. // Ensure image extension is acceptable.
  959. if ( ! in_array( strtolower( pathinfo( $url_info['path'], PATHINFO_EXTENSION ) ), self::$extensions, true ) ) {
  960. return false;
  961. }
  962. // If we got this far, we should have an acceptable image URL
  963. // But let folks filter to decline if they prefer.
  964. /**
  965. * Overwrite the results of the validation steps an image goes through before to be considered valid to be used by Photon.
  966. *
  967. * @module photon
  968. *
  969. * @since 3.0.0
  970. *
  971. * @param bool true Is the image URL valid and can it be used by Photon. Default to true.
  972. * @param string $url Image URL.
  973. * @param array $parsed_url Array of information about the image.
  974. */
  975. return apply_filters( 'photon_validate_image_url', true, $url, $parsed_url );
  976. }
  977. /**
  978. * Checks if the file exists before it passes the file to photon.
  979. *
  980. * @param string $src The image URL.
  981. * @return string
  982. **/
  983. public static function strip_image_dimensions_maybe( $src ) {
  984. $stripped_src = $src;
  985. // Build URL, first removing WP's resized string so we pass the original image to Photon.
  986. if ( preg_match( '#(-\d+x\d+)\.(' . implode( '|', self::$extensions ) . '){1}$#i', $src, $src_parts ) ) {
  987. $stripped_src = str_replace( $src_parts[1], '', $src );
  988. $upload_dir = wp_get_upload_dir();
  989. // Extracts the file path to the image minus the base url.
  990. $file_path = substr( $stripped_src, strlen( $upload_dir['baseurl'] ) );
  991. if ( file_exists( $upload_dir['basedir'] . $file_path ) ) {
  992. $src = $stripped_src;
  993. }
  994. }
  995. return $src;
  996. }
  997. /**
  998. * Provide an array of available image sizes and corresponding dimensions.
  999. * Similar to get_intermediate_image_sizes() except that it includes image sizes' dimensions, not just their names.
  1000. *
  1001. * @global $wp_additional_image_sizes
  1002. * @uses get_option
  1003. * @return array
  1004. */
  1005. protected static function image_sizes() {
  1006. if ( null === self::$image_sizes ) {
  1007. global $_wp_additional_image_sizes;
  1008. // Populate an array matching the data structure of $_wp_additional_image_sizes so we have a consistent structure for image sizes.
  1009. $images = array(
  1010. 'thumb' => array(
  1011. 'width' => (int) get_option( 'thumbnail_size_w' ),
  1012. 'height' => (int) get_option( 'thumbnail_size_h' ),
  1013. 'crop' => (bool) get_option( 'thumbnail_crop' ),
  1014. ),
  1015. 'medium' => array(
  1016. 'width' => (int) get_option( 'medium_size_w' ),
  1017. 'height' => (int) get_option( 'medium_size_h' ),
  1018. 'crop' => false,
  1019. ),
  1020. 'medium_large' => array(
  1021. 'width' => (int) get_option( 'medium_large_size_w' ),
  1022. 'height' => (int) get_option( 'medium_large_size_h' ),
  1023. 'crop' => false,
  1024. ),
  1025. 'large' => array(
  1026. 'width' => (int) get_option( 'large_size_w' ),
  1027. 'height' => (int) get_option( 'large_size_h' ),
  1028. 'crop' => false,
  1029. ),
  1030. 'full' => array(
  1031. 'width' => null,
  1032. 'height' => null,
  1033. 'crop' => false,
  1034. ),
  1035. );
  1036. // Compatibility mapping as found in wp-includes/media.php.
  1037. $images['thumbnail'] = $images['thumb'];
  1038. // Update class variable, merging in $_wp_additional_image_sizes if any are set.
  1039. if ( is_array( $_wp_additional_image_sizes ) && ! empty( $_wp_additional_image_sizes ) ) {
  1040. self::$image_sizes = array_merge( $images, $_wp_additional_image_sizes );
  1041. } else {
  1042. self::$image_sizes = $images;
  1043. }
  1044. }
  1045. return is_array( self::$image_sizes ) ? self::$image_sizes : array();
  1046. }
  1047. /**
  1048. * Pass og:image URLs through Photon
  1049. *
  1050. * @param array $tags Open graph tags.
  1051. * @param array $parameters Image parameters.
  1052. * @uses jetpack_photon_url
  1053. * @return array Open graph tags.
  1054. */
  1055. public function filter_open_graph_tags( $tags, $parameters ) {
  1056. if ( empty( $tags['og:image'] ) ) {
  1057. return $tags;
  1058. }
  1059. $photon_args = array(
  1060. 'fit' => sprintf( '%d,%d', 2 * $parameters['image_width'], 2 * $parameters['image_height'] ),
  1061. );
  1062. if ( is_array( $tags['og:image'] ) ) {
  1063. $images = array();
  1064. foreach ( $tags['og:image'] as $image ) {
  1065. $images[] = jetpack_photon_url( $image, $photon_args );
  1066. }
  1067. $tags['og:image'] = $images;
  1068. } else {
  1069. $tags['og:image'] = jetpack_photon_url( $tags['og:image'], $photon_args );
  1070. }
  1071. return $tags;
  1072. }
  1073. /**
  1074. * Returns empty array.
  1075. *
  1076. * @deprecated 8.8.0 Use filter_photon_noresize_intermediate_sizes.
  1077. *
  1078. * @return array Empty array.
  1079. */
  1080. public function noresize_intermediate_sizes() {
  1081. _deprecated_function( __METHOD__, 'jetpack-8.8.0', '::filter_photon_noresize_intermediate_sizes' );
  1082. return __return_empty_array();
  1083. }
  1084. /**
  1085. * Enqueue Photon helper script
  1086. *
  1087. * @uses wp_enqueue_script, plugins_url
  1088. * @action wp_enqueue_script
  1089. * @return null
  1090. */
  1091. public function action_wp_enqueue_scripts() {
  1092. if ( self::is_amp_endpoint() ) {
  1093. return;
  1094. }
  1095. wp_enqueue_script(
  1096. 'jetpack-photon',
  1097. Assets::get_file_url_for_environment(
  1098. '_inc/build/photon/photon.min.js',
  1099. 'modules/photon/photon.js'
  1100. ),
  1101. array(),
  1102. 20191001,
  1103. true
  1104. );
  1105. }
  1106. /**
  1107. * Determine if image_downsize should utilize Photon via REST API.
  1108. *
  1109. * The WordPress Block Editor (Gutenberg) and other REST API consumers using the wp/v2/media endpoint, especially in the "edit"
  1110. * context is more akin to the is_admin usage of Photon (see filter_image_downsize). Since consumers are trying to edit content in posts,
  1111. * Photon should not fire as it will fire later on display. By aborting an attempt to Photonize an image here, we
  1112. * prevents issues like https://github.com/Automattic/jetpack/issues/10580 .
  1113. *
  1114. * To determine if we're using the wp/v2/media endpoint, we hook onto the `rest_request_before_callbacks` filter and
  1115. * if determined we are using it in the edit context, we'll false out the `jetpack_photon_override_image_downsize` filter.
  1116. *
  1117. * @see Jetpack_Photon::filter_image_downsize()
  1118. *
  1119. * @param null|WP_Error $response REST API response.
  1120. * @param array $endpoint_data Endpoint data. Not used, but part of the filter.
  1121. * @param WP_REST_Request $request Request used to generate the response.
  1122. *
  1123. * @return null|WP_Error The original response object without modification.
  1124. */
  1125. public function should_rest_photon_image_downsize( $response, $endpoint_data, $request ) {
  1126. if ( ! is_a( $request, 'WP_REST_Request' ) ) {
  1127. return $response; // Something odd is happening. Do nothing and return the response.
  1128. }
  1129. if ( is_wp_error( $response ) ) {
  1130. // If we're going to return an error, we don't need to do anything with Photon.
  1131. return $response;
  1132. }
  1133. $this->should_rest_photon_image_downsize_override( $request );
  1134. return $response;
  1135. }
  1136. /**
  1137. * Helper function to check if a WP_REST_Request is the media endpoint in the edit context.
  1138. *
  1139. * @param WP_REST_Request $request The current REST request.
  1140. */
  1141. private function should_rest_photon_image_downsize_override( WP_REST_Request $request ) {
  1142. $route = $request->get_route();
  1143. if (
  1144. (
  1145. false !== strpos( $route, 'wp/v2/media' )
  1146. && 'edit' === $request->get_param( 'context' )
  1147. )
  1148. || false !== strpos( $route, 'wpcom/v2/external-media/copy' )
  1149. ) {
  1150. // Don't use `__return_true()`: Use something unique. See ::_override_image_downsize_in_rest_edit_context()
  1151. // Late execution to avoid conflict with other plugins as we really don't want to run in this situation.
  1152. add_filter(
  1153. 'jetpack_photon_override_image_downsize',
  1154. array(
  1155. $this,
  1156. 'override_image_downsize_in_rest_edit_context',
  1157. ),
  1158. 999999
  1159. );
  1160. }
  1161. }
  1162. /**
  1163. * Brings in should_rest_photon_image_downsize for the rest_after_insert_attachment hook.
  1164. *
  1165. * @since 8.7.0
  1166. *
  1167. * @param WP_Post $attachment Inserted or updated attachment object.
  1168. * @param WP_REST_Request $request Request object.
  1169. */
  1170. public function should_rest_photon_image_downsize_insert_attachment( WP_Post $attachment, WP_REST_Request $request ) {
  1171. if ( ! is_a( $request, 'WP_REST_Request' ) ) {
  1172. // Something odd is happening.
  1173. return;
  1174. }
  1175. $this->should_rest_photon_image_downsize_override( $request );
  1176. }
  1177. /**
  1178. * Remove the override we may have added in ::should_rest_photon_image_downsize()
  1179. * Since ::_override_image_downsize_in_rest_edit_context() is only
  1180. * every used here, we can always remove it without ever worrying
  1181. * about breaking any other configuration.
  1182. *
  1183. * @param mixed $response REST API Response.
  1184. * @return mixed Unchanged $response
  1185. */
  1186. public function cleanup_rest_photon_image_downsize( $response ) {
  1187. remove_filter(
  1188. 'jetpack_photon_override_image_downsize',
  1189. array(
  1190. $this,
  1191. 'override_image_downsize_in_rest_edit_context',
  1192. ),
  1193. 999999
  1194. );
  1195. return $response;
  1196. }
  1197. /**
  1198. * Used internally by ::should_rest_photon_image_downsize() to not photonize
  1199. * image URLs in ?context=edit REST requests.
  1200. * MUST NOT be used anywhere else.
  1201. * We use a unique function instead of __return_true so that we can clean up
  1202. * after ourselves without breaking anyone else's filters.
  1203. *
  1204. * @internal
  1205. * @return true
  1206. */
  1207. public function override_image_downsize_in_rest_edit_context() {
  1208. return true;
  1209. }
  1210. /**
  1211. * Return whether the current page is AMP.
  1212. *
  1213. * This is only present for the sake of WordPress.com where the Jetpack_AMP_Support
  1214. * class does not yet exist. This mehod may only be called at the wp action or later.
  1215. *
  1216. * @return bool Whether AMP page.
  1217. */
  1218. private static function is_amp_endpoint() {
  1219. return class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request();
  1220. }
  1221. }