3 * Press This class and display functionality
6 * @subpackage Press_This
16 // Used to trigger the bookmarklet update notice.
20 private $images = array();
22 private $embeds = array();
32 public function __construct() {}
35 * App and site settings data, including i18n strings for the client-side.
40 * @return array Site settings.
42 public function site_settings() {
45 * Filters whether or not Press This should redirect the user in the parent window upon save.
49 * @param bool $redirect Whether to redirect in parent window or not. Default false.
51 'redirInParent' => apply_filters( 'press_this_redirect_in_parent', false ),
56 * Get the source's images and save them locally, for posterity, unless we can't.
61 * @param int $post_id Post ID.
62 * @param string $content Optional. Current expected markup for Press This. Expects slashed. Default empty.
63 * @return string New markup with old image URLs replaced with the local attachment ones if swapped.
65 public function side_load_images( $post_id, $content = '' ) {
66 $content = wp_unslash( $content );
68 if ( preg_match_all( '/<img [^>]+>/', $content, $matches ) && current_user_can( 'upload_files' ) ) {
69 foreach ( (array) $matches[0] as $image ) {
70 // This is inserted from our JS so HTML attributes should always be in double quotes.
71 if ( ! preg_match( '/src="([^"]+)"/', $image, $url_matches ) ) {
75 $image_src = $url_matches[1];
77 // Don't try to sideload a file without a file extension, leads to WP upload error.
78 if ( ! preg_match( '/[^\?]+\.(?:jpe?g|jpe|gif|png)(?:\?|$)/i', $image_src ) ) {
82 // Sideload image, which gives us a new image src.
83 $new_src = media_sideload_image( $image_src, $post_id, null, 'src' );
85 if ( ! is_wp_error( $new_src ) ) {
86 // Replace the POSTED content <img> with correct uploaded ones.
87 // Need to do it in two steps so we don't replace links to the original image if any.
88 $new_image = str_replace( $image_src, $new_src, $image );
89 $content = str_replace( $image, $new_image, $content );
95 return wp_slash( $content );
99 * Ajax handler for saving the post as draft or published.
104 public function save_post() {
105 if ( empty( $_POST['post_ID'] ) || ! $post_id = (int) $_POST['post_ID'] ) {
106 wp_send_json_error( array( 'errorMessage' => __( 'Missing post ID.' ) ) );
109 if ( empty( $_POST['_wpnonce'] ) || ! wp_verify_nonce( $_POST['_wpnonce'], 'update-post_' . $post_id ) ||
110 ! current_user_can( 'edit_post', $post_id ) ) {
112 wp_send_json_error( array( 'errorMessage' => __( 'Invalid post.' ) ) );
117 'post_title' => ( ! empty( $_POST['post_title'] ) ) ? sanitize_text_field( trim( $_POST['post_title'] ) ) : '',
118 'post_content' => ( ! empty( $_POST['post_content'] ) ) ? trim( $_POST['post_content'] ) : '',
119 'post_type' => 'post',
120 'post_status' => 'draft',
121 'post_format' => ( ! empty( $_POST['post_format'] ) ) ? sanitize_text_field( $_POST['post_format'] ) : '',
124 // Only accept categories if the user actually can assign
125 $category_tax = get_taxonomy( 'category' );
126 if ( current_user_can( $category_tax->cap->assign_terms ) ) {
127 $post_data['post_category'] = ( ! empty( $_POST['post_category'] ) ) ? $_POST['post_category'] : array();
130 // Only accept taxonomies if the user can actually assign
131 if ( ! empty( $_POST['tax_input'] ) ) {
132 $tax_input = $_POST['tax_input'];
133 foreach ( $tax_input as $tax => $_ti ) {
134 $tax_object = get_taxonomy( $tax );
135 if ( ! $tax_object || ! current_user_can( $tax_object->cap->assign_terms ) ) {
136 unset( $tax_input[ $tax ] );
140 $post_data['tax_input'] = $tax_input;
143 // Toggle status to pending if user cannot actually publish
144 if ( ! empty( $_POST['post_status'] ) && 'publish' === $_POST['post_status'] ) {
145 if ( current_user_can( 'publish_posts' ) ) {
146 $post_data['post_status'] = 'publish';
148 $post_data['post_status'] = 'pending';
152 $post_data['post_content'] = $this->side_load_images( $post_id, $post_data['post_content'] );
155 * Filters the post data of a Press This post before saving/updating.
157 * The {@see 'side_load_images'} action has already run at this point.
161 * @param array $post_data The post data.
163 $post_data = apply_filters( 'press_this_save_post', $post_data );
165 $updated = wp_update_post( $post_data, true );
167 if ( is_wp_error( $updated ) ) {
168 wp_send_json_error( array( 'errorMessage' => $updated->get_error_message() ) );
170 if ( isset( $post_data['post_format'] ) ) {
171 if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) ) {
172 set_post_format( $post_id, $post_data['post_format'] );
173 } elseif ( $post_data['post_format'] ) {
174 set_post_format( $post_id, false );
178 $forceRedirect = false;
180 if ( 'publish' === get_post_status( $post_id ) ) {
181 $redirect = get_post_permalink( $post_id );
182 } elseif ( isset( $_POST['pt-force-redirect'] ) && $_POST['pt-force-redirect'] === 'true' ) {
183 $forceRedirect = true;
184 $redirect = get_edit_post_link( $post_id, 'js' );
190 * Filters the URL to redirect to when Press This saves.
194 * @param string $url Redirect URL. If `$status` is 'publish', this will be the post permalink.
195 * Otherwise, the default is false resulting in no redirect.
196 * @param int $post_id Post ID.
197 * @param string $status Post status.
199 $redirect = apply_filters( 'press_this_save_redirect', $redirect, $post_id, $post_data['post_status'] );
202 wp_send_json_success( array( 'redirect' => $redirect, 'force' => $forceRedirect ) );
204 wp_send_json_success( array( 'postSaved' => true ) );
210 * Ajax handler for adding a new category.
215 public function add_category() {
216 if ( false === wp_verify_nonce( $_POST['new_cat_nonce'], 'add-category' ) ) {
217 wp_send_json_error();
220 $taxonomy = get_taxonomy( 'category' );
222 if ( ! current_user_can( $taxonomy->cap->edit_terms ) || empty( $_POST['name'] ) ) {
223 wp_send_json_error();
226 $parent = isset( $_POST['parent'] ) && (int) $_POST['parent'] > 0 ? (int) $_POST['parent'] : 0;
227 $names = explode( ',', $_POST['name'] );
228 $added = $data = array();
230 foreach ( $names as $cat_name ) {
231 $cat_name = trim( $cat_name );
232 $cat_nicename = sanitize_title( $cat_name );
234 if ( empty( $cat_nicename ) ) {
238 // @todo Find a more performant way to check existence, maybe get_term() with a separate parent check.
239 if ( term_exists( $cat_name, $taxonomy->name, $parent ) ) {
240 if ( count( $names ) === 1 ) {
241 wp_send_json_error( array( 'errorMessage' => __( 'This category already exists.' ) ) );
247 $cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) );
249 if ( is_wp_error( $cat_id ) ) {
251 } elseif ( is_array( $cat_id ) ) {
252 $cat_id = $cat_id['term_id'];
258 if ( empty( $added ) ) {
259 wp_send_json_error( array( 'errorMessage' => __( 'This category cannot be added. Please change the name and try again.' ) ) );
262 foreach ( $added as $new_cat_id ) {
263 $new_cat = get_category( $new_cat_id );
265 if ( is_wp_error( $new_cat ) ) {
266 wp_send_json_error( array( 'errorMessage' => __( 'Error while adding the category. Please try again later.' ) ) );
270 'term_id' => $new_cat->term_id,
271 'name' => $new_cat->name,
272 'parent' => $new_cat->parent,
275 wp_send_json_success( $data );
279 * Downloads the source's HTML via server-side call for the given URL.
284 * @param string $url URL to scan.
285 * @return string Source's HTML sanitized markup
287 public function fetch_source_html( $url ) {
288 if ( empty( $url ) ) {
289 return new WP_Error( 'invalid-url', __( 'A valid URL was not provided.' ) );
292 $remote_url = wp_safe_remote_get( $url, array(
294 // Use an explicit user-agent for Press This
295 'user-agent' => 'Press This (WordPress/' . get_bloginfo( 'version' ) . '); ' . get_bloginfo( 'url' )
298 if ( is_wp_error( $remote_url ) ) {
302 $allowed_elements = array(
323 $source_content = wp_remote_retrieve_body( $remote_url );
324 $source_content = wp_kses( $source_content, $allowed_elements );
326 return $source_content;
330 * Utility method to limit an array to 50 values.
335 * @param array $value Array to limit.
336 * @return array Original array if fewer than 50 values, limited array, empty array otherwise.
338 private function _limit_array( $value ) {
339 if ( is_array( $value ) ) {
340 if ( count( $value ) > 50 ) {
341 return array_slice( $value, 0, 50 );
351 * Utility method to limit the length of a given string to 5,000 characters.
356 * @param string $value String to limit.
357 * @return bool|int|string If boolean or integer, that value. If a string, the original value
358 * if fewer than 5,000 characters, a truncated version, otherwise an
361 private function _limit_string( $value ) {
364 if ( is_numeric( $value ) || is_bool( $value ) ) {
366 } else if ( is_string( $value ) ) {
367 if ( mb_strlen( $value ) > 5000 ) {
368 $return = mb_substr( $value, 0, 5000 );
373 $return = html_entity_decode( $return, ENT_QUOTES, 'UTF-8' );
374 $return = sanitize_text_field( trim( $return ) );
381 * Utility method to limit a given URL to 2,048 characters.
386 * @param string $url URL to check for length and validity.
387 * @return string Escaped URL if of valid length (< 2048) and makeup. Empty string otherwise.
389 private function _limit_url( $url ) {
390 if ( ! is_string( $url ) ) {
394 // HTTP 1.1 allows 8000 chars but the "de-facto" standard supported in all current browsers is 2048.
395 if ( strlen( $url ) > 2048 ) {
396 return ''; // Return empty rather than a truncated/invalid URL
399 // Does not look like a URL.
400 if ( ! preg_match( '/^([!#$&-;=?-\[\]_a-z~]|%[0-9a-fA-F]{2})+$/', $url ) ) {
404 // If the URL is root-relative, prepend the protocol and domain name
405 if ( $url && $this->domain && preg_match( '%^/[^/]+%', $url ) ) {
406 $url = $this->domain . $url;
409 // Not absolute or protocol-relative URL.
410 if ( ! preg_match( '%^(?:https?:)?//[^/]+%', $url ) ) {
414 return esc_url_raw( $url, array( 'http', 'https' ) );
418 * Utility method to limit image source URLs.
420 * Excluded URLs include share-this type buttons, loaders, spinners, spacers, WordPress interface images,
421 * tiny buttons or thumbs, mathtag.com or quantserve.com images, or the WordPress.com stats gif.
426 * @param string $src Image source URL.
427 * @return string If not matched an excluded URL type, the original URL, empty string otherwise.
429 private function _limit_img( $src ) {
430 $src = $this->_limit_url( $src );
432 if ( preg_match( '!/ad[sx]?/!i', $src ) ) {
435 } else if ( preg_match( '!(/share-?this[^.]+?\.[a-z0-9]{3,4})(\?.*)?$!i', $src ) ) {
436 // Share-this type button
438 } else if ( preg_match( '!/(spinner|loading|spacer|blank|rss)\.(gif|jpg|png)!i', $src ) ) {
439 // Loaders, spinners, spacers
441 } else if ( preg_match( '!/([^./]+[-_])?(spinner|loading|spacer|blank)s?([-_][^./]+)?\.[a-z0-9]{3,4}!i', $src ) ) {
442 // Fancy loaders, spinners, spacers
444 } else if ( preg_match( '!([^./]+[-_])?thumb[^.]*\.(gif|jpg|png)$!i', $src ) ) {
445 // Thumbnails, too small, usually irrelevant to context
447 } else if ( false !== stripos( $src, '/wp-includes/' ) ) {
448 // Classic WordPress interface images
450 } else if ( preg_match( '![^\d]\d{1,2}x\d+\.(gif|jpg|png)$!i', $src ) ) {
451 // Most often tiny buttons/thumbs (< 100px wide)
453 } else if ( preg_match( '!/pixel\.(mathtag|quantserve)\.com!i', $src ) ) {
454 // See mathtag.com and https://www.quantcast.com/how-we-do-it/iab-standard-measurement/how-we-collect-data/
456 } else if ( preg_match( '!/[gb]\.gif(\?.+)?$!i', $src ) ) {
457 // WordPress.com stats gif
465 * Limit embed source URLs to specific providers.
467 * Not all core oEmbed providers are supported. Supported providers include YouTube, Vimeo,
468 * Vine, Daily Motion, SoundCloud, and Twitter.
473 * @param string $src Embed source URL.
474 * @return string If not from a supported provider, an empty string. Otherwise, a reformatted embed URL.
476 private function _limit_embed( $src ) {
477 $src = $this->_limit_url( $src );
482 if ( preg_match( '!//(m|www)\.youtube\.com/(embed|v)/([^?]+)\?.+$!i', $src, $src_matches ) ) {
483 // Embedded Youtube videos (www or mobile)
484 $src = 'https://www.youtube.com/watch?v=' . $src_matches[3];
485 } else if ( preg_match( '!//player\.vimeo\.com/video/([\d]+)([?/].*)?$!i', $src, $src_matches ) ) {
486 // Embedded Vimeo iframe videos
487 $src = 'https://vimeo.com/' . (int) $src_matches[1];
488 } else if ( preg_match( '!//vimeo\.com/moogaloop\.swf\?clip_id=([\d]+)$!i', $src, $src_matches ) ) {
489 // Embedded Vimeo Flash videos
490 $src = 'https://vimeo.com/' . (int) $src_matches[1];
491 } else if ( preg_match( '!//vine\.co/v/([^/]+)/embed!i', $src, $src_matches ) ) {
492 // Embedded Vine videos
493 $src = 'https://vine.co/v/' . $src_matches[1];
494 } else if ( preg_match( '!//(www\.)?dailymotion\.com/embed/video/([^/?]+)([/?].+)?!i', $src, $src_matches ) ) {
495 // Embedded Daily Motion videos
496 $src = 'https://www.dailymotion.com/video/' . $src_matches[2];
498 $oembed = _wp_oembed_get_object();
500 if ( ! $oembed->get_provider( $src, array( 'discover' => false ) ) ) {
509 * Process a meta data entry from the source.
514 * @param string $meta_name Meta key name.
515 * @param mixed $meta_value Meta value.
516 * @param array $data Associative array of source data.
517 * @return array Processed data array.
519 private function _process_meta_entry( $meta_name, $meta_value, $data ) {
520 if ( preg_match( '/:?(title|description|keywords|site_name)$/', $meta_name ) ) {
521 $data['_meta'][ $meta_name ] = $meta_value;
523 switch ( $meta_name ) {
526 case 'og:video:secure_url':
527 $meta_value = $this->_limit_embed( $meta_value );
529 if ( ! isset( $data['_embeds'] ) ) {
530 $data['_embeds'] = array();
533 if ( ! empty( $meta_value ) && ! in_array( $meta_value, $data['_embeds'] ) ) {
534 $data['_embeds'][] = $meta_value;
539 case 'og:image:secure_url':
540 case 'twitter:image0:src':
541 case 'twitter:image0':
542 case 'twitter:image:src':
543 case 'twitter:image':
544 $meta_value = $this->_limit_img( $meta_value );
546 if ( ! isset( $data['_images'] ) ) {
547 $data['_images'] = array();
550 if ( ! empty( $meta_value ) && ! in_array( $meta_value, $data['_images'] ) ) {
551 $data['_images'][] = $meta_value;
562 * Fetches and parses _meta, _images, and _links data from the source.
567 * @param string $url URL to scan.
568 * @param array $data Optional. Existing data array if you have one. Default empty array.
569 * @return array New data array.
571 public function source_data_fetch_fallback( $url, $data = array() ) {
572 if ( empty( $url ) ) {
576 // Download source page to tmp file.
577 $source_content = $this->fetch_source_html( $url );
578 if ( is_wp_error( $source_content ) ) {
579 return array( 'errors' => $source_content->get_error_messages() );
582 // Fetch and gather <meta> data first, so discovered media is offered 1st to user.
583 if ( empty( $data['_meta'] ) ) {
584 $data['_meta'] = array();
587 if ( preg_match_all( '/<meta [^>]+>/', $source_content, $matches ) ) {
588 $items = $this->_limit_array( $matches[0] );
590 foreach ( $items as $value ) {
591 if ( preg_match( '/(property|name)="([^"]+)"[^>]+content="([^"]+)"/', $value, $new_matches ) ) {
592 $meta_name = $this->_limit_string( $new_matches[2] );
593 $meta_value = $this->_limit_string( $new_matches[3] );
595 // Sanity check. $key is usually things like 'title', 'description', 'keywords', etc.
596 if ( strlen( $meta_name ) > 100 ) {
600 $data = $this->_process_meta_entry( $meta_name, $meta_value, $data );
605 // Fetch and gather <img> data.
606 if ( empty( $data['_images'] ) ) {
607 $data['_images'] = array();
610 if ( preg_match_all( '/<img [^>]+>/', $source_content, $matches ) ) {
611 $items = $this->_limit_array( $matches[0] );
613 foreach ( $items as $value ) {
614 if ( ( preg_match( '/width=(\'|")(\d+)\\1/i', $value, $new_matches ) && $new_matches[2] < 256 ) ||
615 ( preg_match( '/height=(\'|")(\d+)\\1/i', $value, $new_matches ) && $new_matches[2] < 128 ) ) {
620 if ( preg_match( '/src=(\'|")([^\'"]+)\\1/i', $value, $new_matches ) ) {
621 $src = $this->_limit_img( $new_matches[2] );
622 if ( ! empty( $src ) && ! in_array( $src, $data['_images'] ) ) {
623 $data['_images'][] = $src;
629 // Fetch and gather <iframe> data.
630 if ( empty( $data['_embeds'] ) ) {
631 $data['_embeds'] = array();
634 if ( preg_match_all( '/<iframe [^>]+>/', $source_content, $matches ) ) {
635 $items = $this->_limit_array( $matches[0] );
637 foreach ( $items as $value ) {
638 if ( preg_match( '/src=(\'|")([^\'"]+)\\1/', $value, $new_matches ) ) {
639 $src = $this->_limit_embed( $new_matches[2] );
641 if ( ! empty( $src ) && ! in_array( $src, $data['_embeds'] ) ) {
642 $data['_embeds'][] = $src;
648 // Fetch and gather <link> data.
649 if ( empty( $data['_links'] ) ) {
650 $data['_links'] = array();
653 if ( preg_match_all( '/<link [^>]+>/', $source_content, $matches ) ) {
654 $items = $this->_limit_array( $matches[0] );
656 foreach ( $items as $value ) {
657 if ( preg_match( '/rel=["\'](canonical|shortlink|icon)["\']/i', $value, $matches_rel ) && preg_match( '/href=[\'"]([^\'" ]+)[\'"]/i', $value, $matches_url ) ) {
658 $rel = $matches_rel[1];
659 $url = $this->_limit_url( $matches_url[1] );
661 if ( ! empty( $url ) && empty( $data['_links'][ $rel ] ) ) {
662 $data['_links'][ $rel ] = $url;
672 * Handles backward-compat with the legacy version of Press This by supporting its query string params.
679 public function merge_or_fetch_data() {
680 // Get data from $_POST and $_GET, as appropriate ($_POST > $_GET), to remain backward compatible.
683 // Only instantiate the keys we want. Sanity check and sanitize each one.
684 foreach ( array( 'u', 's', 't', 'v' ) as $key ) {
685 if ( ! empty( $_POST[ $key ] ) ) {
686 $value = wp_unslash( $_POST[ $key ] );
687 } else if ( ! empty( $_GET[ $key ] ) ) {
688 $value = wp_unslash( $_GET[ $key ] );
693 if ( 'u' === $key ) {
694 $value = $this->_limit_url( $value );
696 if ( preg_match( '%^(?:https?:)?//[^/]+%i', $value, $domain_match ) ) {
697 $this->domain = $domain_match[0];
700 $value = $this->_limit_string( $value );
703 if ( ! empty( $value ) ) {
704 $data[ $key ] = $value;
709 * Filters whether to enable in-source media discovery in Press This.
713 * @param bool $enable Whether to enable media discovery.
715 if ( apply_filters( 'enable_press_this_media_discovery', true ) ) {
717 * If no title, _images, _embed, and _meta was passed via $_POST, fetch data from source as fallback,
718 * making PT fully backward compatible with the older bookmarklet.
720 if ( empty( $_POST ) && ! empty( $data['u'] ) ) {
721 $data = $this->source_data_fetch_fallback( $data['u'], $data );
723 foreach ( array( '_images', '_embeds' ) as $type ) {
724 if ( empty( $_POST[ $type ] ) ) {
728 $data[ $type ] = array();
729 $items = $this->_limit_array( $_POST[ $type ] );
731 foreach ( $items as $key => $value ) {
732 if ( $type === '_images' ) {
733 $value = $this->_limit_img( wp_unslash( $value ) );
735 $value = $this->_limit_embed( wp_unslash( $value ) );
738 if ( ! empty( $value ) ) {
739 $data[ $type ][] = $value;
744 foreach ( array( '_meta', '_links' ) as $type ) {
745 if ( empty( $_POST[ $type ] ) ) {
749 $data[ $type ] = array();
750 $items = $this->_limit_array( $_POST[ $type ] );
752 foreach ( $items as $key => $value ) {
753 // Sanity check. These are associative arrays, $key is usually things like 'title', 'description', 'keywords', etc.
754 if ( empty( $key ) || strlen( $key ) > 100 ) {
758 if ( $type === '_meta' ) {
759 $value = $this->_limit_string( wp_unslash( $value ) );
761 if ( ! empty( $value ) ) {
762 $data = $this->_process_meta_entry( $key, $value, $data );
765 if ( in_array( $key, array( 'canonical', 'shortlink', 'icon' ), true ) ) {
766 $data[ $type ][ $key ] = $this->_limit_url( wp_unslash( $value ) );
773 // Support passing a single image src as `i`
774 if ( ! empty( $_REQUEST['i'] ) && ( $img_src = $this->_limit_img( wp_unslash( $_REQUEST['i'] ) ) ) ) {
775 if ( empty( $data['_images'] ) ) {
776 $data['_images'] = array( $img_src );
777 } elseif ( ! in_array( $img_src, $data['_images'], true ) ) {
778 array_unshift( $data['_images'], $img_src );
784 * Filters the Press This data array.
788 * @param array $data Press This Data array.
790 return apply_filters( 'press_this_data', $data );
794 * Adds another stylesheet inside TinyMCE.
799 * @param string $styles URL to editor stylesheet.
800 * @return string Possibly modified stylesheets list.
802 public function add_editor_style( $styles ) {
803 if ( ! empty( $styles ) ) {
807 $press_this = admin_url( 'css/press-this-editor.css' );
809 $press_this = str_replace( '.css', '-rtl.css', $press_this );
812 return $styles . $press_this;
816 * Outputs the post format selection HTML.
821 * @param WP_Post $post Post object.
823 public function post_formats_html( $post ) {
824 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) ) {
825 $post_formats = get_theme_support( 'post-formats' );
827 if ( is_array( $post_formats[0] ) ) {
828 $post_format = get_post_format( $post->ID );
830 if ( ! $post_format ) {
834 // Add in the current one if it isn't there yet, in case the current theme doesn't support it.
835 if ( $post_format && ! in_array( $post_format, $post_formats[0] ) ) {
836 $post_formats[0][] = $post_format;
840 <div id="post-formats-select">
841 <fieldset><legend class="screen-reader-text"><?php _e( 'Post Formats' ); ?></legend>
842 <input type="radio" name="post_format" class="post-format" id="post-format-0" value="0" <?php checked( $post_format, '0' ); ?> />
843 <label for="post-format-0" class="post-format-icon post-format-standard"><?php echo get_post_format_string( 'standard' ); ?></label>
846 foreach ( $post_formats[0] as $format ) {
847 $attr_format = esc_attr( $format );
850 <input type="radio" name="post_format" class="post-format" id="post-format-<?php echo $attr_format; ?>" value="<?php echo $attr_format; ?>" <?php checked( $post_format, $format ); ?> />
851 <label for="post-format-<?php echo $attr_format ?>" class="post-format-icon post-format-<?php echo $attr_format; ?>"><?php echo esc_html( get_post_format_string( $format ) ); ?></label>
864 * Outputs the categories HTML.
869 * @param WP_Post $post Post object.
871 public function categories_html( $post ) {
872 $taxonomy = get_taxonomy( 'category' );
874 // Bail if user cannot assign terms
875 if ( ! current_user_can( $taxonomy->cap->assign_terms ) ) {
879 // Only show "add" if user can edit terms
880 if ( current_user_can( $taxonomy->cap->edit_terms ) ) {
882 <button type="button" class="add-cat-toggle button-link" aria-expanded="false">
883 <span class="dashicons dashicons-plus"></span><span class="screen-reader-text"><?php _e( 'Toggle add category' ); ?></span>
885 <div class="add-category is-hidden">
886 <label class="screen-reader-text" for="new-category"><?php echo $taxonomy->labels->add_new_item; ?></label>
887 <input type="text" id="new-category" class="add-category-name" placeholder="<?php echo esc_attr( $taxonomy->labels->new_item_name ); ?>" value="" aria-required="true">
888 <label class="screen-reader-text" for="new-category-parent"><?php echo $taxonomy->labels->parent_item_colon; ?></label>
889 <div class="postform-wrapper">
891 wp_dropdown_categories( array(
892 'taxonomy' => 'category',
894 'name' => 'new-category-parent',
897 'show_option_none' => '— ' . $taxonomy->labels->parent_item . ' —'
901 <button type="button" class="add-cat-submit"><?php _e( 'Add' ); ?></button>
907 <div class="categories-search-wrapper">
908 <input id="categories-search" type="search" class="categories-search" placeholder="<?php esc_attr_e( 'Search categories by name' ) ?>">
909 <label for="categories-search">
910 <span class="dashicons dashicons-search"></span><span class="screen-reader-text"><?php _e( 'Search categories' ); ?></span>
913 <div aria-label="<?php esc_attr_e( 'Categories' ); ?>">
914 <ul class="categories-select">
915 <?php wp_terms_checklist( $post->ID, array( 'taxonomy' => 'category', 'list_only' => true ) ); ?>
922 * Outputs the tags HTML.
927 * @param WP_Post $post Post object.
929 public function tags_html( $post ) {
930 $taxonomy = get_taxonomy( 'post_tag' );
931 $user_can_assign_terms = current_user_can( $taxonomy->cap->assign_terms );
932 $esc_tags = get_terms_to_edit( $post->ID, 'post_tag' );
934 if ( ! $esc_tags || is_wp_error( $esc_tags ) ) {
939 <div class="tagsdiv" id="post_tag">
941 <input type="hidden" name="tax_input[post_tag]" class="the-tags" value="<?php echo $esc_tags; // escaped in get_terms_to_edit() ?>">
944 if ( $user_can_assign_terms ) {
946 <div class="ajaxtag hide-if-no-js">
947 <label class="screen-reader-text" for="new-tag-post_tag"><?php _e( 'Tags' ); ?></label>
949 <input type="text" id="new-tag-post_tag" name="newtag[post_tag]" class="newtag form-input-tip" size="16" autocomplete="off" value="" aria-describedby="new-tag-desc" />
950 <button type="button" class="tagadd"><?php _e( 'Add' ); ?></button>
953 <p class="howto" id="new-tag-desc">
954 <?php echo $taxonomy->labels->separate_items_with_commas; ?>
961 <div class="tagchecklist"></div>
965 if ( $user_can_assign_terms ) {
967 <button type="button" class="button-link tagcloud-link" id="link-post_tag" aria-expanded="false"><?php echo $taxonomy->labels->choose_from_most_used; ?></button>
973 * Get a list of embeds with no duplicates.
978 * @param array $data The site's data.
979 * @return array Embeds selected to be available.
981 public function get_embeds( $data ) {
982 $selected_embeds = array();
984 // Make sure to add the Pressed page if it's a valid oembed itself
985 if ( ! empty ( $data['u'] ) && $this->_limit_embed( $data['u'] ) ) {
986 $data['_embeds'][] = $data['u'];
989 if ( ! empty( $data['_embeds'] ) ) {
990 foreach ( $data['_embeds'] as $src ) {
991 $prot_relative_src = preg_replace( '/^https?:/', '', $src );
993 if ( in_array( $prot_relative_src, $this->embeds ) ) {
997 $selected_embeds[] = $src;
998 $this->embeds[] = $prot_relative_src;
1002 return $selected_embeds;
1006 * Get a list of images with no duplicates.
1011 * @param array $data The site's data.
1014 public function get_images( $data ) {
1015 $selected_images = array();
1017 if ( ! empty( $data['_images'] ) ) {
1018 foreach ( $data['_images'] as $src ) {
1019 if ( false !== strpos( $src, 'gravatar.com' ) ) {
1020 $src = preg_replace( '%http://[\d]+\.gravatar\.com/%', 'https://secure.gravatar.com/', $src );
1023 $prot_relative_src = preg_replace( '/^https?:/', '', $src );
1025 if ( in_array( $prot_relative_src, $this->images ) ||
1026 ( false !== strpos( $src, 'avatar' ) && count( $this->images ) > 15 ) ) {
1027 // Skip: already selected or some type of avatar and we've already gathered more than 15 images.
1031 $selected_images[] = $src;
1032 $this->images[] = $prot_relative_src;
1036 return $selected_images;
1040 * Gets the source page's canonical link, based on passed location and meta data.
1045 * @param array $data The site's data.
1046 * @return string Discovered canonical URL, or empty
1048 public function get_canonical_link( $data ) {
1051 if ( ! empty( $data['_links']['canonical'] ) ) {
1052 $link = $data['_links']['canonical'];
1053 } elseif ( ! empty( $data['u'] ) ) {
1055 } elseif ( ! empty( $data['_meta'] ) ) {
1056 if ( ! empty( $data['_meta']['twitter:url'] ) ) {
1057 $link = $data['_meta']['twitter:url'];
1058 } else if ( ! empty( $data['_meta']['og:url'] ) ) {
1059 $link = $data['_meta']['og:url'];
1063 if ( empty( $link ) && ! empty( $data['_links']['shortlink'] ) ) {
1064 $link = $data['_links']['shortlink'];
1071 * Gets the source page's site name, based on passed meta data.
1076 * @param array $data The site's data.
1077 * @return string Discovered site name, or empty
1079 public function get_source_site_name( $data ) {
1082 if ( ! empty( $data['_meta'] ) ) {
1083 if ( ! empty( $data['_meta']['og:site_name'] ) ) {
1084 $name = $data['_meta']['og:site_name'];
1085 } else if ( ! empty( $data['_meta']['application-name'] ) ) {
1086 $name = $data['_meta']['application-name'];
1094 * Gets the source page's title, based on passed title and meta data.
1099 * @param array $data The site's data.
1100 * @return string Discovered page title, or empty
1102 public function get_suggested_title( $data ) {
1105 if ( ! empty( $data['t'] ) ) {
1106 $title = $data['t'];
1107 } elseif ( ! empty( $data['_meta'] ) ) {
1108 if ( ! empty( $data['_meta']['twitter:title'] ) ) {
1109 $title = $data['_meta']['twitter:title'];
1110 } else if ( ! empty( $data['_meta']['og:title'] ) ) {
1111 $title = $data['_meta']['og:title'];
1112 } else if ( ! empty( $data['_meta']['title'] ) ) {
1113 $title = $data['_meta']['title'];
1121 * Gets the source page's suggested content, based on passed data (description, selection, etc).
1123 * Features a blockquoted excerpt, as well as content attribution, if any.
1128 * @param array $data The site's data.
1129 * @return string Discovered content, or empty
1131 public function get_suggested_content( $data ) {
1132 $content = $text = '';
1134 if ( ! empty( $data['s'] ) ) {
1136 } else if ( ! empty( $data['_meta'] ) ) {
1137 if ( ! empty( $data['_meta']['twitter:description'] ) ) {
1138 $text = $data['_meta']['twitter:description'];
1139 } else if ( ! empty( $data['_meta']['og:description'] ) ) {
1140 $text = $data['_meta']['og:description'];
1141 } else if ( ! empty( $data['_meta']['description'] ) ) {
1142 $text = $data['_meta']['description'];
1145 // If there is an ellipsis at the end, the description is very likely auto-generated. Better to ignore it.
1146 if ( $text && substr( $text, -3 ) === '...' ) {
1151 $default_html = array( 'quote' => '', 'link' => '', 'embed' => '' );
1153 if ( ! empty( $data['u'] ) && $this->_limit_embed( $data['u'] ) ) {
1154 $default_html['embed'] = '<p>[embed]' . $data['u'] . '[/embed]</p>';
1156 if ( ! empty( $data['s'] ) ) {
1157 // If the user has selected some text, do quote it.
1158 $default_html['quote'] = '<blockquote>%1$s</blockquote>';
1161 $default_html['quote'] = '<blockquote>%1$s</blockquote>';
1162 $default_html['link'] = '<p>' . _x( 'Source:', 'Used in Press This to indicate where the content comes from.' ) .
1163 ' <em><a href="%1$s">%2$s</a></em></p>';
1167 * Filters the default HTML tags used in the suggested content for the editor.
1169 * The HTML strings use printf format. After filtering the content is added at the specified places with `sprintf()`.
1173 * @param array $default_html Associative array with three possible keys:
1174 * - 'quote' where %1$s is replaced with the site description or the selected content.
1175 * - 'link' where %1$s is link href, %2$s is link text, usually the source page title.
1176 * - 'embed' which contains an [embed] shortcode when the source page offers embeddable content.
1177 * @param array $data Associative array containing the data from the source page.
1179 $default_html = apply_filters( 'press_this_suggested_html', $default_html, $data );
1181 if ( ! empty( $default_html['embed'] ) ) {
1182 $content .= $default_html['embed'];
1185 // Wrap suggested content in the specified HTML.
1186 if ( ! empty( $default_html['quote'] ) && $text ) {
1187 $content .= sprintf( $default_html['quote'], $text );
1190 // Add source attribution if there is one available.
1191 if ( ! empty( $default_html['link'] ) ) {
1192 $title = $this->get_suggested_title( $data );
1193 $url = $this->get_canonical_link( $data );
1196 $title = $this->get_source_site_name( $data );
1199 if ( $url && $title ) {
1200 $content .= sprintf( $default_html['link'], $url, $title );
1208 * Serves the app's base HTML, which in turns calls the load script.
1213 * @global WP_Locale $wp_locale
1214 * @global bool $is_IE
1216 public function html() {
1219 $wp_version = get_bloginfo( 'version' );
1221 // Get data, new (POST) and old (GET).
1222 $data = $this->merge_or_fetch_data();
1224 $post_title = $this->get_suggested_title( $data );
1226 $post_content = $this->get_suggested_content( $data );
1228 // Get site settings array/data.
1229 $site_settings = $this->site_settings();
1231 // Pass the images and embeds
1232 $images = $this->get_images( $data );
1233 $embeds = $this->get_embeds( $data );
1236 'v' => ! empty( $data['v'] ) ? $data['v'] : '',
1237 'u' => ! empty( $data['u'] ) ? $data['u'] : '',
1238 'hasData' => ! empty( $data ),
1241 if ( ! empty( $images ) ) {
1242 $site_data['_images'] = $images;
1245 if ( ! empty( $embeds ) ) {
1246 $site_data['_embeds'] = $embeds;
1249 // Add press-this-editor.css and remove theme's editor-style.css, if any.
1250 remove_editor_styles();
1252 add_filter( 'mce_css', array( $this, 'add_editor_style' ) );
1254 if ( ! empty( $GLOBALS['is_IE'] ) ) {
1255 @header( 'X-UA-Compatible: IE=edge' );
1258 @header( 'Content-Type: ' . get_option( 'html_type' ) . '; charset=' . get_option( 'blog_charset' ) );
1262 <!--[if IE 7]> <html class="lt-ie9 lt-ie8" <?php language_attributes(); ?>> <![endif]-->
1263 <!--[if IE 8]> <html class="lt-ie9" <?php language_attributes(); ?>> <![endif]-->
1264 <!--[if gt IE 8]><!--> <html <?php language_attributes(); ?>> <!--<![endif]-->
1266 <meta http-equiv="Content-Type" content="<?php echo esc_attr( get_bloginfo( 'html_type' ) ); ?>; charset=<?php echo esc_attr( get_option( 'blog_charset' ) ); ?>" />
1267 <meta name="viewport" content="width=device-width">
1268 <title><?php esc_html_e( 'Press This!' ) ?></title>
1271 window.wpPressThisData = <?php echo wp_json_encode( $site_data ); ?>;
1272 window.wpPressThisConfig = <?php echo wp_json_encode( $site_settings ); ?>;
1275 <script type="text/javascript">
1276 var ajaxurl = '<?php echo esc_js( admin_url( 'admin-ajax.php', 'relative' ) ); ?>',
1277 pagenow = 'press-this',
1279 adminpage = 'press-this-php',
1280 thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
1281 decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
1282 isRtl = <?php echo (int) is_rtl(); ?>;
1287 * $post->ID is needed for the embed shortcode so we can show oEmbed previews in the editor.
1288 * Maybe find a way without it.
1290 $post = get_default_post_to_edit( 'post', true );
1291 $post_ID = (int) $post->ID;
1293 wp_enqueue_media( array( 'post' => $post_ID ) );
1294 wp_enqueue_style( 'press-this' );
1295 wp_enqueue_script( 'press-this' );
1296 wp_enqueue_script( 'json2' );
1297 wp_enqueue_script( 'editor' );
1299 $categories_tax = get_taxonomy( 'category' );
1300 $show_categories = current_user_can( $categories_tax->cap->assign_terms ) || current_user_can( $categories_tax->cap->edit_terms );
1302 $tag_tax = get_taxonomy( 'post_tag' );
1303 $show_tags = current_user_can( $tag_tax->cap->assign_terms );
1305 $supports_formats = false;
1308 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) ) {
1309 $supports_formats = true;
1311 if ( ! ( $post_format = get_post_format( $post_ID ) ) ) {
1316 /** This action is documented in wp-admin/admin-header.php */
1317 do_action( 'admin_enqueue_scripts', 'press-this.php' );
1319 /** This action is documented in wp-admin/admin-header.php */
1320 do_action( 'admin_print_styles-press-this.php' );
1322 /** This action is documented in wp-admin/admin-header.php */
1323 do_action( 'admin_print_styles' );
1325 /** This action is documented in wp-admin/admin-header.php */
1326 do_action( 'admin_print_scripts-press-this.php' );
1328 /** This action is documented in wp-admin/admin-header.php */
1329 do_action( 'admin_print_scripts' );
1331 /** This action is documented in wp-admin/admin-header.php */
1332 do_action( 'admin_head-press-this.php' );
1334 /** This action is documented in wp-admin/admin-header.php */
1335 do_action( 'admin_head' );
1340 $admin_body_class = 'press-this';
1341 $admin_body_class .= ( is_rtl() ) ? ' rtl' : '';
1342 $admin_body_class .= ' branch-' . str_replace( array( '.', ',' ), '-', floatval( $wp_version ) );
1343 $admin_body_class .= ' version-' . str_replace( '.', '-', preg_replace( '/^([.0-9]+).*/', '$1', $wp_version ) );
1344 $admin_body_class .= ' admin-color-' . sanitize_html_class( get_user_option( 'admin_color' ), 'fresh' );
1345 $admin_body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_user_locale() ) ) );
1347 /** This filter is documented in wp-admin/admin-header.php */
1348 $admin_body_classes = apply_filters( 'admin_body_class', '' );
1351 <body class="wp-admin wp-core-ui <?php echo $admin_body_classes . ' ' . $admin_body_class; ?>">
1352 <div id="adminbar" class="adminbar">
1353 <h1 id="current-site" class="current-site">
1354 <a class="current-site-link" href="<?php echo esc_url( home_url( '/' ) ); ?>" target="_blank" rel="home">
1355 <span class="dashicons dashicons-wordpress"></span>
1356 <span class="current-site-name"><?php bloginfo( 'name' ); ?></span>
1359 <button type="button" class="options button-link closed">
1360 <span class="dashicons dashicons-tag on-closed"></span>
1361 <span class="screen-reader-text on-closed"><?php _e( 'Show post options' ); ?></span>
1362 <span aria-hidden="true" class="on-open"><?php _e( 'Done' ); ?></span>
1363 <span class="screen-reader-text on-open"><?php _e( 'Hide post options' ); ?></span>
1367 <div id="scanbar" class="scan">
1369 <label for="url-scan" class="screen-reader-text"><?php _e( 'Scan site for content' ); ?></label>
1370 <input type="url" name="u" id="url-scan" class="scan-url" value="" placeholder="<?php esc_attr_e( 'Enter a URL to scan' ) ?>" />
1371 <input type="submit" name="url-scan-submit" id="url-scan-submit" class="scan-submit" value="<?php esc_attr_e( 'Scan' ) ?>" />
1375 <form id="pressthis-form" method="post" action="post.php" autocomplete="off">
1376 <input type="hidden" name="post_ID" id="post_ID" value="<?php echo $post_ID; ?>" />
1377 <input type="hidden" name="action" value="press-this-save-post" />
1378 <input type="hidden" name="post_status" id="post_status" value="draft" />
1379 <input type="hidden" name="wp-preview" id="wp-preview" value="" />
1380 <input type="hidden" name="post_title" id="post_title" value="" />
1381 <input type="hidden" name="pt-force-redirect" id="pt-force-redirect" value="" />
1384 wp_nonce_field( 'update-post_' . $post_ID, '_wpnonce', false );
1385 wp_nonce_field( 'add-category', '_ajax_nonce-add-category', false );
1389 <div class="wrapper">
1390 <div class="editor-wrapper">
1391 <div class="alerts" role="alert" aria-live="assertive" aria-relevant="all" aria-atomic="true">
1394 if ( isset( $data['v'] ) && $this->version > $data['v'] ) {
1396 <p class="alert is-notice">
1397 <?php printf( __( 'You should upgrade <a href="%s" target="_blank">your bookmarklet</a> to the latest version!' ), admin_url( 'tools.php' ) ); ?>
1405 <div id="app-container" class="editor">
1406 <span id="title-container-label" class="post-title-placeholder" aria-hidden="true"><?php _e( 'Post title' ); ?></span>
1407 <h2 id="title-container" class="post-title" contenteditable="true" spellcheck="true" aria-label="<?php esc_attr_e( 'Post title' ); ?>" tabindex="0"><?php echo esc_html( $post_title ); ?></h2>
1409 <div class="media-list-container">
1410 <div class="media-list-inner-container">
1411 <h2 class="screen-reader-text"><?php _e( 'Suggested media' ); ?></h2>
1412 <ul class="media-list"></ul>
1417 wp_editor( $post_content, 'pressthis', array(
1418 'drag_drop_upload' => true,
1419 'editor_height' => 600,
1420 'media_buttons' => false,
1421 'textarea_name' => 'post_content',
1425 'wordpress_adv_hidden' => false,
1426 'add_unload_trigger' => false,
1427 'statusbar' => false,
1428 'autoresize_min_height' => 600,
1429 'wp_autoresize_on' => true,
1430 'plugins' => 'lists,media,paste,tabfocus,fullscreen,wordpress,wpautoresize,wpeditimage,wpgallery,wplink,wptextpattern,wpview',
1431 'toolbar1' => 'bold,italic,bullist,numlist,blockquote,link,unlink',
1432 'toolbar2' => 'undo,redo',
1434 'quicktags' => array(
1435 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,more',
1443 <div class="options-panel-back is-hidden" tabindex="-1"></div>
1444 <div class="options-panel is-off-screen is-hidden" tabindex="-1">
1445 <div class="post-options">
1447 <?php if ( $supports_formats ) : ?>
1448 <button type="button" class="button-link post-option">
1449 <span class="dashicons dashicons-admin-post"></span>
1450 <span class="post-option-title"><?php _ex( 'Format', 'post format' ); ?></span>
1451 <span class="post-option-contents" id="post-option-post-format"><?php echo esc_html( get_post_format_string( $post_format ) ); ?></span>
1452 <span class="dashicons post-option-forward"></span>
1456 <?php if ( $show_categories ) : ?>
1457 <button type="button" class="button-link post-option">
1458 <span class="dashicons dashicons-category"></span>
1459 <span class="post-option-title"><?php _e( 'Categories' ); ?></span>
1460 <span class="dashicons post-option-forward"></span>
1464 <?php if ( $show_tags ) : ?>
1465 <button type="button" class="button-link post-option">
1466 <span class="dashicons dashicons-tag"></span>
1467 <span class="post-option-title"><?php _e( 'Tags' ); ?></span>
1468 <span class="dashicons post-option-forward"></span>
1473 <?php if ( $supports_formats ) : ?>
1474 <div class="setting-modal is-off-screen is-hidden">
1475 <button type="button" class="button-link modal-close">
1476 <span class="dashicons post-option-back"></span>
1477 <span class="setting-title" aria-hidden="true"><?php _ex( 'Format', 'post format' ); ?></span>
1478 <span class="screen-reader-text"><?php _e( 'Back to post options' ) ?></span>
1480 <?php $this->post_formats_html( $post ); ?>
1484 <?php if ( $show_categories ) : ?>
1485 <div class="setting-modal is-off-screen is-hidden">
1486 <button type="button" class="button-link modal-close">
1487 <span class="dashicons post-option-back"></span>
1488 <span class="setting-title" aria-hidden="true"><?php _e( 'Categories' ); ?></span>
1489 <span class="screen-reader-text"><?php _e( 'Back to post options' ) ?></span>
1491 <?php $this->categories_html( $post ); ?>
1495 <?php if ( $show_tags ) : ?>
1496 <div class="setting-modal tags is-off-screen is-hidden">
1497 <button type="button" class="button-link modal-close">
1498 <span class="dashicons post-option-back"></span>
1499 <span class="setting-title" aria-hidden="true"><?php _e( 'Tags' ); ?></span>
1500 <span class="screen-reader-text"><?php _e( 'Back to post options' ) ?></span>
1502 <?php $this->tags_html( $post ); ?>
1505 </div><!-- .options-panel -->
1506 </div><!-- .wrapper -->
1508 <div class="press-this-actions">
1509 <div class="pressthis-media-buttons">
1510 <button type="button" class="insert-media button-link" data-editor="pressthis">
1511 <span class="dashicons dashicons-admin-media"></span>
1512 <span class="screen-reader-text"><?php _e( 'Add Media' ); ?></span>
1515 <div class="post-actions">
1516 <span class="spinner"> </span>
1517 <div class="split-button">
1518 <div class="split-button-head">
1519 <button type="button" class="publish-button split-button-primary" aria-live="polite">
1520 <span class="publish"><?php echo ( current_user_can( 'publish_posts' ) ) ? __( 'Publish' ) : __( 'Submit for Review' ); ?></span>
1521 <span class="saving-draft"><?php _e( 'Saving…' ); ?></span>
1522 </button><button type="button" class="split-button-toggle" aria-haspopup="true" aria-expanded="false">
1523 <i class="dashicons dashicons-arrow-down-alt2"></i>
1524 <span class="screen-reader-text"><?php _e('More actions'); ?></span>
1527 <ul class="split-button-body">
1528 <li><button type="button" class="button-link draft-button split-button-option"><?php _e( 'Save Draft' ); ?></button></li>
1529 <li><button type="button" class="button-link standard-editor-button split-button-option"><?php _e( 'Standard Editor' ); ?></button></li>
1530 <li><button type="button" class="button-link preview-button split-button-option"><?php _e( 'Preview' ); ?></button></li>
1538 /** This action is documented in wp-admin/admin-footer.php */
1539 do_action( 'admin_footer' );
1541 /** This action is documented in wp-admin/admin-footer.php */
1542 do_action( 'admin_print_footer_scripts-press-this.php' );
1544 /** This action is documented in wp-admin/admin-footer.php */
1545 do_action( 'admin_print_footer_scripts' );
1547 /** This action is documented in wp-admin/admin-footer.php */
1548 do_action( 'admin_footer-press-this.php' );