PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.2.2
Jetpack – WP Security, Backup, Speed, & Growth v10.2.2
16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 All 502 releases
jetpack / modules / markdown / easy-markdown.php

easy-markdown.php in Jetpack – WP Security, Backup, Speed, & Growth 10.2.2, at modules/markdown/easy-markdown.php

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