Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
15.38% covered (danger)
15.38%
40 / 260
2.17% covered (danger)
2.17%
1 / 46
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCom_Markdown
15.56% covered (danger)
15.56%
40 / 257
2.17% covered (danger)
2.17%
1 / 46
8788.47
0.00% covered (danger)
0.00%
0 / 1
 get_instance
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 load
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 maybe_unload_for_bulk_edit
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 maybe_load_actions_and_filters
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
 load_markdown_for_posts
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 unload_markdown_for_posts
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 load_markdown_for_comments
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 unload_markdown_for_comments
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 add_o2_helpers
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 o2_preview_post
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 o2_preview_comment
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 o2_escape_lists
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 o2_unescape_lists
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 preserve_code_blocks
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_remove_kses
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 register_setting
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 sanitize_setting
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 post_field
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 comment_field
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 get_support_url
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_posting_enabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_commenting_enabled
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_markdown
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 set_as_markdown
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_parser
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 add_default_post_type_support
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 get_post_screen_post_type
n/a
0 / 0
n/a
0 / 0
5
 edit_post_content
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 edit_post_content_filtered
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
30
 wp_kses_allowed_html
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
6.04
 after_wp_tiny_mce
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
2
 wp_insert_post_data
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
132
 wp_insert_post
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 pre_comment_content
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 comment_hash
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 transform
88.46% covered (warning)
88.46%
23 / 26
0.00% covered (danger)
0.00%
0 / 1
6.06
 wp_post_revision_fields
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 wp_restore_post_revision
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 fix_latest_revision_on_restore
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 xmlrpc_actions
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 check_for_early_methods
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 prime_post_cache
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 swap_for_editing
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 uncache_munged_posts
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 make_filterable
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 the_posts
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php //phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Plugin URI: https://automattic.com/
4 * Plugin Name: Easy Markdown
5 * Description: Write in Markdown, publish in WordPress
6 * Version: 0.1
7 * Author: Matt Wiebe
8 * Author URI: https://automattic.com/
9 * Text Domain: jetpack
10 *
11 * @package automattic/jetpack
12 */
13
14/**
15 * Copyright (c) Automattic. All rights reserved.
16 *
17 * Released under the GPL license
18 * https://www.opensource.org/licenses/gpl-license.php
19 *
20 * This is an add-on for WordPress
21 * https://wordpress.org/
22 *
23 * **********************************************************************
24 * This program is free software; you can redistribute it and/or modify
25 * it under the terms of the GNU General Public License as published by
26 * the Free Software Foundation; either version 2 of the License, or
27 * (at your option) any later version.
28 *
29 * This program is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32 * GNU General Public License for more details.
33 * **********************************************************************
34 */
35
36if ( ! defined( 'ABSPATH' ) ) {
37    exit( 0 );
38}
39
40/**
41 * WPCom_Markdown class.
42 */
43class WPCom_Markdown {
44
45    const POST_OPTION       = 'wpcom_publish_posts_with_markdown';
46    const COMMENT_OPTION    = 'wpcom_publish_comments_with_markdown';
47    const POST_TYPE_SUPPORT = 'wpcom-markdown';
48    const IS_MD_META        = '_wpcom_is_markdown';
49
50    /**
51     * Our markdown parser.
52     *
53     * @var WPCom_GHF_Markdown_Parser
54     */
55    private static $parser;
56
57    /**
58     * Whether the parser is loading. Loading it translates strings, which can run kses, and so our
59     * kses filter, before the parser exists.
60     *
61     * @var bool
62     */
63    private static $is_loading_parser = false;
64
65    /**
66     * An instance of the markdown class.
67     *
68     * @var WPCom_Markdown
69     */
70    private static $instance;
71
72    /**
73     * To ensure that our munged posts over xml-rpc are removed from the cache.
74     *
75     * @var array
76     */
77    public $posts_to_uncache = array();
78
79    /**
80     * Posts and parents to monitor.
81     *
82     * @var array
83     */
84    private $monitoring = array(
85        'post'   => array(),
86        'parent' => array(),
87    );
88
89    /**
90     * Whether or not kses filters were removed. Only set if removal was attempted.
91     *
92     * @var ?bool
93     */
94    public $kses;
95
96    /**
97     * Yay singletons!
98     *
99     * @return object WPCom_Markdown instance
100     */
101    public static function get_instance() {
102        if ( ! self::$instance ) {
103            self::$instance = new self();
104        }
105        return self::$instance;
106    }
107
108    /**
109     * Kicks things off on `init` action
110     */
111    public function load() {
112        $this->add_default_post_type_support();
113        $this->maybe_load_actions_and_filters();
114        if ( defined( 'REST_API_REQUEST' ) && REST_API_REQUEST ) {
115            // phpcs:ignore WPCUT.SwitchBlog.SwitchBlog -- wpcom flags **every** use of switch_blog, apparently expecting valid instances to ignore or suppress the sniff.
116            add_action( 'switch_blog', array( $this, 'maybe_load_actions_and_filters' ), 10, 2 );
117        }
118        add_action( 'admin_init', array( $this, 'register_setting' ) );
119        add_action( 'admin_init', array( $this, 'maybe_unload_for_bulk_edit' ) );
120        if ( current_theme_supports( 'o2' ) || class_exists( 'P2' ) ) {
121            $this->add_o2_helpers();
122        }
123    }
124
125    /**
126     * If we're in a bulk edit session, unload so that we don't lose our markdown metadata
127     */
128    public function maybe_unload_for_bulk_edit() {
129        if ( isset( $_REQUEST['bulk_edit'] ) && $this->is_posting_enabled() ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
130            $this->unload_markdown_for_posts();
131        }
132    }
133
134    /**
135     * Called on init and fires on switch_blog to decide if our actions and filters
136     * should be running.
137     *
138     * @param int|null $new_blog_id New blog ID.
139     * @param int|null $old_blog_id Old blog ID.
140     * @return null
141     */
142    public function maybe_load_actions_and_filters( $new_blog_id = null, $old_blog_id = null ) {
143
144        // When WP sites are being installed, the options table is not available yet.
145        if ( function_exists( 'wp_installing' ) && wp_installing() ) {
146            return;
147        }
148
149        // If this is a switch_to_blog call, and the blog isn't changing, we'll already be loaded.
150        if ( $new_blog_id && $new_blog_id === $old_blog_id ) {
151            return;
152        }
153
154        if ( $this->is_posting_enabled() ) {
155            $this->load_markdown_for_posts();
156        } else {
157            $this->unload_markdown_for_posts();
158        }
159
160        if ( $this->is_commenting_enabled() ) {
161            $this->load_markdown_for_comments();
162        } else {
163            $this->unload_markdown_for_comments();
164        }
165    }
166
167    /**
168     * Set up hooks for enabling Markdown conversion on posts
169     */
170    public function load_markdown_for_posts() {
171        add_filter( 'wp_kses_allowed_html', array( $this, 'wp_kses_allowed_html' ), 10, 2 );
172        add_action( 'after_wp_tiny_mce', array( $this, 'after_wp_tiny_mce' ) );
173        add_action( 'wp_insert_post', array( $this, 'wp_insert_post' ) );
174        add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
175        add_filter( 'edit_post_content', array( $this, 'edit_post_content' ), 10, 2 );
176        add_filter( 'edit_post_content_filtered', array( $this, 'edit_post_content_filtered' ), 10, 2 );
177        add_action( 'wp_restore_post_revision', array( $this, 'wp_restore_post_revision' ), 10, 2 );
178        add_filter( '_wp_post_revision_fields', array( $this, 'wp_post_revision_fields' ) );
179        add_action( 'xmlrpc_call', array( $this, 'xmlrpc_actions' ) );
180        add_filter( 'content_save_pre', array( $this, 'preserve_code_blocks' ), 1 );
181        if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
182            $this->check_for_early_methods();
183        }
184    }
185
186    /**
187     * Removes hooks to disable Markdown conversion on posts
188     */
189    public function unload_markdown_for_posts() {
190        remove_filter( 'wp_kses_allowed_html', array( $this, 'wp_kses_allowed_html' ) );
191        remove_action( 'after_wp_tiny_mce', array( $this, 'after_wp_tiny_mce' ) );
192        remove_action( 'wp_insert_post', array( $this, 'wp_insert_post' ) );
193        remove_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10 );
194        remove_filter( 'edit_post_content', array( $this, 'edit_post_content' ), 10 );
195        remove_filter( 'edit_post_content_filtered', array( $this, 'edit_post_content_filtered' ), 10 );
196        remove_action( 'wp_restore_post_revision', array( $this, 'wp_restore_post_revision' ), 10 );
197        remove_filter( '_wp_post_revision_fields', array( $this, 'wp_post_revision_fields' ) );
198        remove_action( 'xmlrpc_call', array( $this, 'xmlrpc_actions' ) );
199        remove_filter( 'content_save_pre', array( $this, 'preserve_code_blocks' ), 1 );
200    }
201
202    /**
203     * Set up hooks for enabling Markdown conversion on comments
204     */
205    protected function load_markdown_for_comments() {
206        // Use priority 9 so that Markdown runs before KSES, which can clean up
207        // any munged HTML.
208        add_filter( 'pre_comment_content', array( $this, 'pre_comment_content' ), 9 );
209    }
210
211    /**
212     * Removes hooks to disable Markdown conversion
213     */
214    protected function unload_markdown_for_comments() {
215        remove_filter( 'pre_comment_content', array( $this, 'pre_comment_content' ), 9 );
216    }
217
218    /**
219     * The o2 plugin does some of what we do. Let's take precedence.
220     */
221    public function add_o2_helpers() {
222        if ( $this->is_posting_enabled() ) {
223            add_filter( 'content_save_pre', array( $this, 'o2_escape_lists' ), 1 );
224        }
225
226        add_filter( 'o2_preview_post', array( $this, 'o2_preview_post' ) );
227        add_filter( 'o2_preview_comment', array( $this, 'o2_preview_comment' ) );
228
229        add_filter( 'wpcom_markdown_transform_pre', array( $this, 'o2_unescape_lists' ) );
230        add_filter( 'wpcom_untransformed_content', array( $this, 'o2_unescape_lists' ) );
231    }
232
233    /**
234     * If Markdown is enabled for posts on this blog, filter the text for o2 previews
235     *
236     * @param  string $text Post text.
237     * @return string       Post text transformed through the magic of Markdown
238     */
239    public function o2_preview_post( $text ) {
240        if ( $this->is_posting_enabled() ) {
241            $text = $this->transform( $text, array( 'unslash' => false ) );
242        }
243        return $text;
244    }
245
246    /**
247     * If Markdown is enabled for comments on this blog, filter the text for o2 previews
248     *
249     * @param  string $text Comment text.
250     * @return string       Comment text transformed through the magic of Markdown
251     */
252    public function o2_preview_comment( $text ) {
253        if ( $this->is_commenting_enabled() ) {
254            $text = $this->transform( $text, array( 'unslash' => false ) );
255        }
256        return $text;
257    }
258
259    /**
260     * Escapes lists so that o2 doesn't trounce them
261     *
262     * @param  string $text Post/comment text.
263     * @return string       Text escaped with HTML entity for asterisk.
264     */
265    public function o2_escape_lists( $text ) {
266        return preg_replace( '/^\\* /um', '&#42; ', $text );
267    }
268
269    /**
270     * Unescapes the token we inserted on o2_escape_lists
271     *
272     * @param  string $text Post/comment text with HTML entities for asterisks.
273     * @return string       Text with the HTML entity removed
274     */
275    public function o2_unescape_lists( $text ) {
276        return preg_replace( '/^[&]\#042; /um', '* ', $text );
277    }
278
279    /**
280     * Preserve code blocks from being munged by KSES before they have a chance
281     *
282     * @param  string $text post content.
283     * @return string       post content with code blocks escaped.
284     */
285    public function preserve_code_blocks( $text ) {
286        return $this->get_parser()->codeblock_preserve( $text );
287    }
288
289    /**
290     * Remove KSES if it's there. Store the result to manually invoke later if needed.
291     */
292    public function maybe_remove_kses() {
293        // Filters return true if they existed before you removed them.
294        if ( $this->is_posting_enabled() ) {
295            $this->kses = remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' ) && remove_filter( 'content_save_pre', 'wp_filter_post_kses' );
296        }
297    }
298
299    /**
300     * Add our Writing and Discussion settings.
301     */
302    public function register_setting() {
303        add_settings_field( self::POST_OPTION, __( 'Markdown', 'jetpack' ), array( $this, 'post_field' ), 'writing' );
304        register_setting( 'writing', self::POST_OPTION, array( $this, 'sanitize_setting' ) );
305        add_settings_field( self::COMMENT_OPTION, __( 'Markdown', 'jetpack' ), array( $this, 'comment_field' ), 'discussion' );
306        register_setting( 'discussion', self::COMMENT_OPTION, array( $this, 'sanitize_setting' ) );
307    }
308
309    /**
310     * Sanitize setting. Don't really want to store "on" value, so we'll store "1" instead!
311     *
312     * @param  string $input Value received by settings API via $_POST.
313     * @return bool          Cast to boolean.
314     */
315    public function sanitize_setting( $input ) {
316        return (bool) $input;
317    }
318
319    /**
320     * Prints HTML for the Writing setting
321     */
322    public function post_field() {
323        printf(
324            '<label><input name="%1$s" id="%1$s" type="checkbox"%2$s /> %3$s</label><p class="description">%4$s</p>',
325            esc_attr( self::POST_OPTION ),
326            checked( $this->is_posting_enabled(), true, false ),
327            esc_html__( 'Use Markdown for posts and pages.', 'jetpack' ),
328            sprintf( '<a href="%s" data-target="wpcom-help-center">%s</a>', esc_url( $this->get_support_url() ), esc_html__( 'Learn more about Markdown.', 'jetpack' ) )
329        );
330    }
331
332    /**
333     * Prints HTML for the Discussion setting
334     */
335    public function comment_field() {
336        printf(
337            '<label><input name="%1$s" id="%1$s" type="checkbox"%2$s /> %3$s</label><p class="description">%4$s</p>',
338            esc_attr( self::COMMENT_OPTION ),
339            checked( $this->is_commenting_enabled(), true, false ),
340            esc_html__( 'Use Markdown for comments.', 'jetpack' ),
341            sprintf( '<a href="%s" data-target="wpcom-help-center">%s</a>', esc_url( $this->get_support_url() ), esc_html__( 'Learn more about Markdown.', 'jetpack' ) )
342        );
343    }
344
345    /**
346     * Get the support url for Markdown
347     *
348     * @uses   apply_filters
349     * @return string support url
350     */
351    protected function get_support_url() {
352        /**
353         * Filter the Markdown support URL.
354         *
355         * @module markdown
356         *
357         * @since 2.8.0
358         *
359         * @param string $url Markdown support URL.
360         */
361        return apply_filters( 'easy_markdown_support_url', 'https://en.support.wordpress.com/markdown-quick-reference/' );
362    }
363
364    /**
365     * Is Mardown conversion for posts enabled?
366     *
367     * @return boolean
368     */
369    public function is_posting_enabled() {
370        return (bool) Jetpack_Options::get_option_and_ensure_autoload( self::POST_OPTION, '' );
371    }
372
373    /**
374     * Is Markdown conversion for comments enabled?
375     *
376     * @return boolean
377     */
378    public function is_commenting_enabled() {
379        return (bool) Jetpack_Options::get_option_and_ensure_autoload( self::COMMENT_OPTION, '' );
380    }
381
382    /**
383     * Check if a $post_id has Markdown enabled
384     *
385     * @param  int $post_id A post ID.
386     * @return boolean
387     */
388    public function is_markdown( $post_id ) {
389        return get_metadata( 'post', $post_id, self::IS_MD_META, true );
390    }
391
392    /**
393     * Set Markdown as enabled on a post_id. We skip over update_postmeta so we
394     * can sneakily set metadata on post revisions, which we need.
395     *
396     * @param int $post_id A post ID.
397     * @return bool  The metadata was successfully set.
398     */
399    protected function set_as_markdown( $post_id ) {
400        return update_metadata( 'post', $post_id, self::IS_MD_META, true );
401    }
402
403    /**
404     * Get our Markdown parser object, optionally requiring all of our needed classes and
405     * instantiating our parser.
406     *
407     * @return object WPCom_GHF_Markdown_Parser instance.
408     */
409    public function get_parser() {
410
411        if ( ! self::$parser ) {
412            self::$is_loading_parser = true;
413            require_once JETPACK__PLUGIN_DIR . '/_inc/lib/markdown.php';
414            self::$parser            = new WPCom_GHF_Markdown_Parser();
415            self::$is_loading_parser = false;
416        }
417
418        return self::$parser;
419    }
420
421    /**
422     * We don't want Markdown conversion all over the place.
423     */
424    public function add_default_post_type_support() {
425        add_post_type_support( 'post', self::POST_TYPE_SUPPORT );
426        add_post_type_support( 'page', self::POST_TYPE_SUPPORT );
427        add_post_type_support( 'revision', self::POST_TYPE_SUPPORT );
428    }
429
430    /**
431     * Figure out the post type of the post screen we're on
432     *
433     * @deprecated since 10.8
434     * @return string Current post_type
435     */
436    protected function get_post_screen_post_type() {
437        _deprecated_function( __METHOD__, 'jetpack-10.8', '' );
438
439        global $pagenow;
440        $post_type = filter_input( INPUT_GET, 'post_type', FILTER_UNSAFE_RAW );
441        $post_id   = filter_input( INPUT_GET, 'post', FILTER_SANITIZE_NUMBER_INT );
442
443        if ( 'post-new.php' === $pagenow ) {
444            return ! empty( $post_type ) ? $post_type : 'post';
445        }
446
447        if ( $post_id ) {
448            $post_type = get_post_type( $post_id );
449        }
450
451        return ! empty( $post_type ) ? $post_type : 'post';
452    }
453
454    /**
455     * Swap post_content and post_content_filtered for editing
456     *
457     * @param  string $content Post content.
458     * @param  int    $id         post ID.
459     * @return string          Swapped content
460     */
461    public function edit_post_content( $content, $id ) {
462        if ( $this->is_markdown( $id ) ) {
463            $post = get_post( $id );
464            if ( $post && ! empty( $post->post_content_filtered ) ) {
465                $post = $this->swap_for_editing( $post );
466                return $post->post_content;
467            }
468        }
469        return $content;
470    }
471
472    /**
473     * Swap post_content_filtered and post_content for editing
474     *
475     * @param  string $content Post content_filtered.
476     * @param  int    $id         post ID.
477     * @return string          Swapped content
478     */
479    public function edit_post_content_filtered( $content, $id ) {
480        // if markdown was disabled, let's turn this off.
481        if ( ! $this->is_posting_enabled() && $this->is_markdown( $id ) ) {
482            $post = get_post( $id );
483            if ( $post && ! empty( $post->post_content_filtered ) ) {
484                $content = '';
485            }
486        }
487        return $content;
488    }
489
490    /**
491     * Some tags are allowed to have a 'markdown' attribute, allowing them to contain Markdown.
492     * We need to tell KSES about those tags.
493     *
494     * @param  array  $tags     List of tags that KSES allows.
495     * @param  string $context The context that KSES is allowing these tags.
496     * @return array           The tags that KSES allows, with our extra 'markdown' parameter where necessary.
497     */
498    public function wp_kses_allowed_html( $tags, $context ) {
499        if ( 'post' !== $context || self::$is_loading_parser ) {
500            return $tags;
501        }
502
503        $re = '/' . $this->get_parser()->contain_span_tags_re . '/';
504        foreach ( $tags as $tag => $attributes ) {
505
506            // In case other filters have changed the value to a non-array, we skip it.
507            if ( ! is_array( $attributes ) ) {
508                continue;
509            }
510
511            if ( preg_match( $re, $tag ) ) {
512                $attributes['markdown'] = true;
513                $tags[ $tag ]           = $attributes;
514            }
515        }
516
517        return $tags;
518    }
519
520    /**
521     * TinyMCE needs to know not to strip the 'markdown' attribute. Unfortunately, it doesn't
522     * really offer a nice API for allowed attributes, so we have to manually add it
523     * to the schema instead.
524     */
525    public function after_wp_tiny_mce() {
526        ?>
527<script type="text/javascript">
528jQuery( function() {
529    ( 'undefined' !== typeof tinymce ) && tinymce.on( 'AddEditor', function( event ) {
530        event.editor.on( 'BeforeSetContent', function( event ) {
531            var editor = event.target;
532            Object.keys( editor.schema.elements ).forEach( function( key, index ) {
533                editor.schema.elements[ key ].attributes['markdown'] = {};
534                editor.schema.elements[ key ].attributesOrder.push( 'markdown' );
535            } );
536        } );
537    }, true );
538} );
539</script>
540        <?php
541    }
542
543    /**
544     * Magic happens here. Markdown is converted and stored on post_content. Original Markdown is stored
545     * in post_content_filtered so that we can continue editing as Markdown.
546     *
547     * @param  array $post_data  The post data that will be inserted into the DB. Slashed.
548     * @param  array $postarr    All the stuff that was in $_POST.
549     * @return array             $post_data with post_content and post_content_filtered modified
550     */
551    public function wp_insert_post_data( $post_data, $postarr ) {
552        // $post_data array is slashed!
553        $post_id = $postarr['ID'] ?? false;
554        // bail early if markdown is disabled or this post type is unsupported.
555        if ( ! $this->is_posting_enabled() || ! post_type_supports( $post_data['post_type'], self::POST_TYPE_SUPPORT ) ) {
556            // it's disabled, but maybe this *was* a markdown post before.
557            if ( $this->is_markdown( $post_id ) && ! empty( $post_data['post_content_filtered'] ) ) {
558                $post_data['post_content_filtered'] = '';
559            }
560            // we have no context to determine supported post types in the `post_content_pre` hook,
561            // which already ran to sanitize code blocks. Undo that.
562            $post_data['post_content'] = $this->get_parser()->codeblock_restore( $post_data['post_content'] );
563            return $post_data;
564        }
565        // rejigger post_content and post_content_filtered
566        // revisions are already in the right place, except when we're restoring, but that's taken care of elsewhere
567        // also prevent quick edit feature from overriding already-saved markdown (issue https://github.com/Automattic/jetpack/issues/636).
568        if ( 'revision' !== $post_data['post_type'] && ! isset( $_POST['_inline_edit'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
569            /**
570             * Filter the original post content passed to Markdown.
571             *
572             * @module markdown
573             *
574             * @since 2.8.0
575             *
576             * @param string $post_data['post_content'] Untransformed post content.
577             */
578            $post_data['post_content_filtered'] = apply_filters( 'wpcom_untransformed_content', $post_data['post_content'] );
579            $post_data['post_content']          = $this->transform( $post_data['post_content'], array( 'id' => $post_id ) );
580            /** This filter is already documented in core/wp-includes/default-filters.php */
581            $post_data['post_content'] = apply_filters( 'content_save_pre', $post_data['post_content'] );
582        } elseif ( str_starts_with( $post_data['post_name'], $post_data['post_parent'] . '-autosave' ) ) {
583            // autosaves for previews are weird.
584            /** This filter is already documented in modules/markdown/easy-markdown.php */
585            $post_data['post_content_filtered'] = apply_filters( 'wpcom_untransformed_content', $post_data['post_content'] );
586            $post_data['post_content']          = $this->transform( $post_data['post_content'], array( 'id' => $post_data['post_parent'] ) );
587            /** This filter is already documented in core/wp-includes/default-filters.php */
588            $post_data['post_content'] = apply_filters( 'content_save_pre', $post_data['post_content'] );
589        }
590
591        // set as markdown on the wp_insert_post hook later.
592        if ( $post_id ) {
593            $this->monitoring['post'][ $post_id ] = true;
594        } else {
595            $this->monitoring['content'] = wp_unslash( $post_data['post_content'] );
596        }
597        if ( 'revision' === $postarr['post_type'] && $this->is_markdown( $postarr['post_parent'] ) ) {
598            $this->monitoring['parent'][ $postarr['post_parent'] ] = true;
599        }
600
601        return $post_data;
602    }
603
604    /**
605     * Calls on wp_insert_post action, after wp_insert_post_data. This way we can
606     * still set postmeta on our revisions after it's all been deleted.
607     *
608     * @param  int $post_id The post ID that has just been added/updated.
609     */
610    public function wp_insert_post( $post_id ) {
611        $post_parent = get_post_field( 'post_parent', $post_id );
612        // this didn't have an ID yet. Compare the content that was just saved.
613        if ( isset( $this->monitoring['content'] ) && get_post_field( 'post_content', $post_id ) === $this->monitoring['content'] ) {
614            unset( $this->monitoring['content'] );
615            $this->set_as_markdown( $post_id );
616        }
617        if ( isset( $this->monitoring['post'][ $post_id ] ) ) {
618            unset( $this->monitoring['post'][ $post_id ] );
619            $this->set_as_markdown( $post_id );
620        } elseif ( isset( $this->monitoring['parent'][ $post_parent ] ) ) {
621            unset( $this->monitoring['parent'][ $post_parent ] );
622            $this->set_as_markdown( $post_id );
623        }
624    }
625
626    /**
627     * Run a comment through Markdown. Easy peasy.
628     *
629     * @param  string $content - the content.
630     * @return string
631     */
632    public function pre_comment_content( $content ) {
633        return $this->transform(
634            $content,
635            array(
636                'id' => $this->comment_hash( $content ),
637            )
638        );
639    }
640
641    /**
642     * Return a comment hash.
643     *
644     * @param string $content - the content of the comment.
645     */
646    protected function comment_hash( $content ) {
647        return 'c-' . substr( md5( $content ), 0, 8 );
648    }
649
650    /**
651     * Markdown conversion. Some DRYness for repetitive tasks.
652     *
653     * @param  string $text  Content to be run through Markdown.
654     * @param  array  $args  Arguments, with keys:
655     *                       id: provide a string to prefix footnotes with a unique identifier
656     *                       unslash: when true, expects and returns slashed data
657     *                       decode_code_blocks: when true, assume that text in fenced code blocks is already
658     *                         HTML encoded and should be decoded before being passed to Markdown, which does
659     *                         its own encoding.
660     * @return string        Markdown-processed content
661     */
662    public function transform( $text, $args = array() ) {
663        // If this contains Gutenberg content, let's keep it intact.
664        if ( has_blocks( $text ) ) {
665            return $text;
666        }
667
668        $args = wp_parse_args(
669            $args,
670            array(
671                'id'                 => false,
672                'unslash'            => true,
673                'decode_code_blocks' => ! $this->get_parser()->use_code_shortcode,
674            )
675        );
676        // probably need to unslash.
677        if ( $args['unslash'] ) {
678            $text = wp_unslash( $text );
679        }
680
681        /**
682         * Filter the content to be run through Markdown, before it's transformed by Markdown.
683         *
684         * @module markdown
685         *
686         * @since 2.8.0
687         *
688         * @param string $text Content to be run through Markdown
689         * @param array $args Array of Markdown options.
690         */
691        $text = apply_filters( 'wpcom_markdown_transform_pre', $text, $args ) ?? '';
692        // ensure our paragraphs are separated.
693        $text = str_replace( array( '</p><p>', "</p>\n<p>" ), "</p>\n\n<p>", $text );
694        // visual editor likes to add <p>s. Buh-bye.
695        $text = $this->get_parser()->unp( $text );
696        // sometimes we get an encoded > at start of line, breaking blockquotes.
697        $text = preg_replace( '/^&gt;/m', '>', $text );
698        // prefixes are because we need to namespace footnotes by post_id.
699        $this->get_parser()->fn_id_prefix = $args['id'] ? $args['id'] . '-' : '';
700        // If we're not using the code shortcode, prevent over-encoding.
701        if ( $args['decode_code_blocks'] ) {
702            $text = $this->get_parser()->codeblock_restore( $text );
703        }
704        // Transform it!
705        $text = $this->get_parser()->transform( $text );
706        // Fix footnotes - kses doesn't like the : IDs it supplies.
707        $text = preg_replace( '/((id|href)="#?fn(ref)?):/', '$1-', $text );
708        // Markdown inserts extra spaces to make itself work. Buh-bye.
709        $text = rtrim( $text );
710        /**
711         * Filter the content to be run through Markdown, after it was transformed by Markdown.
712         *
713         * @module markdown
714         *
715         * @since 2.8.0
716         *
717         * @param string $text Content to be run through Markdown
718         * @param array $args Array of Markdown options.
719         */
720        $text = apply_filters( 'wpcom_markdown_transform_post', $text, $args );
721
722        // probably need to re-slash.
723        if ( $args['unslash'] ) {
724            $text = wp_slash( $text );
725        }
726
727        return $text;
728    }
729
730    /**
731     * Shows Markdown in the Revisions screen, and ensures that post_content_filtered
732     * is maintained on revisions
733     *
734     * @param array $fields  Post fields pertinent to revisions.
735     */
736    public function wp_post_revision_fields( $fields ) {
737        $fields['post_content_filtered'] = __( 'Markdown content', 'jetpack' );
738        return $fields;
739    }
740
741    /**
742     * Do some song and dance to keep all post_content and post_content_filtered content
743     * in the expected place when a post revision is restored.
744     *
745     * @param  int $post_id        The post ID have a restore done to it.
746     * @param  int $revision_id    The revision ID being restored.
747     */
748    public function wp_restore_post_revision( $post_id, $revision_id ) {
749        if ( $this->is_markdown( $revision_id ) ) {
750            $revision             = get_post( $revision_id, ARRAY_A );
751            $post                 = get_post( $post_id, ARRAY_A );
752            $post['post_content'] = $revision['post_content_filtered']; // Yes, we put it in post_content, because our wp_insert_post_data() expects that.
753            // set this flag so we can restore the post_content_filtered on the last revision later.
754            $this->monitoring['restore'] = true;
755            // let's not make a revision of our fixing update.
756            add_filter( 'wp_revisions_to_keep', '__return_false', 99 );
757            wp_update_post( $post );
758            $this->fix_latest_revision_on_restore( $post_id );
759            remove_filter( 'wp_revisions_to_keep', '__return_false', 99 );
760        }
761    }
762
763    /**
764     * We need to ensure the last revision has Markdown, not HTML in its post_content_filtered
765     * column after a restore.
766     *
767     * @param  int $post_id The post ID that was just restored.
768     */
769    protected function fix_latest_revision_on_restore( $post_id ) {
770        global $wpdb;
771        $post                                 = get_post( $post_id );
772        $last_revision                        = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_type = 'revision' AND post_parent = %d ORDER BY ID DESC", $post->ID ) );
773        $last_revision->post_content_filtered = $post->post_content_filtered;
774        wp_insert_post( (array) $last_revision );
775    }
776
777    /**
778     * Kicks off magic for an XML-RPC session. We want to keep editing Markdown
779     * and publishing HTML.
780     *
781     * @param  string $xmlrpc_method The current XML-RPC method.
782     */
783    public function xmlrpc_actions( $xmlrpc_method ) {
784        switch ( $xmlrpc_method ) {
785            case 'metaWeblog.getRecentPosts':
786            case 'wp.getPosts':
787            case 'wp.getPages':
788                add_action( 'parse_query', array( $this, 'make_filterable' ), 10, 1 );
789                break;
790            case 'wp.getPost':
791                $this->prime_post_cache();
792                break;
793        }
794    }
795
796    /**
797     * Function metaWeblog.getPost and wp.getPage fire xmlrpc_call action *after* get_post() is called.
798     * So, we have to detect those methods and prime the post cache early.
799     *
800     * @return null
801     */
802    protected function check_for_early_methods() {
803        $raw_post_data = file_get_contents( 'php://input' );
804        if ( ! str_contains( $raw_post_data, 'metaWeblog.getPost' )
805            && ! str_contains( $raw_post_data, 'wp.getPage' ) ) {
806            return;
807        }
808        include_once ABSPATH . WPINC . '/class-IXR.php';
809        $message = new IXR_Message( $raw_post_data );
810        $message->parse();
811        $post_id_position = 'metaWeblog.getPost' === $message->methodName ? 0 : 1; // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
812        $this->prime_post_cache( $message->params[ $post_id_position ] ?? false );
813    }
814
815    /**
816     * Prime the post cache with swapped post_content. This is a sneaky way of getting around
817     * the fact that there are no good hooks to call on the *.getPost xmlrpc methods.
818     *
819     * @param bool $post_id - the post ID that we're priming.
820     */
821    private function prime_post_cache( $post_id = false ) {
822        global $wp_xmlrpc_server;
823        if ( ! $post_id ) {
824            if ( isset( $wp_xmlrpc_server->message->params[3] ) ) {
825                $post_id = $wp_xmlrpc_server->message->params[3];
826            } else {
827                return; // Exit early if we can't get a valid post_id
828            }
829        }
830
831        // prime the post cache.
832        if ( $this->is_markdown( $post_id ) ) {
833            $post = get_post( $post_id );
834            if ( ! empty( $post->post_content_filtered ) ) {
835                wp_cache_delete( $post->ID, 'posts' );
836                $post = $this->swap_for_editing( $post );
837                wp_cache_add( $post->ID, $post, 'posts' );
838                $this->posts_to_uncache[] = $post_id;
839            }
840        }
841        // uncache munged posts if using a persistent object cache.
842        if ( wp_using_ext_object_cache() ) {
843            add_action( 'shutdown', array( $this, 'uncache_munged_posts' ) );
844        }
845    }
846
847    /**
848     * Swaps `post_content_filtered` back to `post_content` for editing purposes.
849     *
850     * @param  object $post WP_Post object.
851     * @return object WP_Post object with swapped `post_content_filtered` and `post_content`.
852     */
853    protected function swap_for_editing( $post ) {
854        $markdown = $post->post_content_filtered;
855        // unencode encoded code blocks.
856        $markdown = $this->get_parser()->codeblock_restore( $markdown );
857        // restore beginning of line blockquotes.
858        $markdown                    = preg_replace( '/^&gt; /m', '> ', $markdown );
859        $post->post_content_filtered = $post->post_content;
860        $post->post_content          = $markdown;
861        return $post;
862    }
863
864    /**
865     * We munge the post cache to serve proper markdown content to XML-RPC clients.
866     * Uncache these after the XML-RPC session ends.
867     */
868    public function uncache_munged_posts() {
869        // $this context gets lost in testing sometimes. Weird.
870        foreach ( self::get_instance()->posts_to_uncache as $post_id ) {
871            wp_cache_delete( $post_id, 'posts' );
872        }
873    }
874
875    /**
876     * Since *.(get)?[Rr]ecentPosts calls get_posts with suppress filters on, we need to
877     * turn them back on so that we can swap things for editing.
878     *
879     * @param object $wp_query WP_Query object.
880     */
881    public function make_filterable( $wp_query ) {
882        $wp_query->set( 'suppress_filters', false );
883        add_action( 'the_posts', array( $this, 'the_posts' ), 10, 2 );
884    }
885
886    /**
887     * Swaps post_content and post_content_filtered for editing.
888     *
889     * @param array $posts Posts returned by the just-completed query.
890     * @return array Modified $posts
891     */
892    public function the_posts( $posts ) {
893        foreach ( $posts as $key => $post ) {
894            if ( $this->is_markdown( $post->ID ) && ! empty( $posts[ $key ]->post_content_filtered ) ) {
895                $markdown                             = $posts[ $key ]->post_content_filtered;
896                $posts[ $key ]->post_content_filtered = $posts[ $key ]->post_content;
897                $posts[ $key ]->post_content          = $markdown;
898            }
899        }
900        return $posts;
901    }
902
903    /**
904     * Singleton silence is golden
905     */
906    private function __construct() {}
907}
908
909add_action( 'init', array( WPCom_Markdown::get_instance(), 'load' ) );