-
Notifications
You must be signed in to change notification settings - Fork 113
/
Copy pathsync-discourse-topic.php
308 lines (263 loc) · 10.2 KB
/
sync-discourse-topic.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php
/**
* Uses a Discourse webhook to sync topics with their associated WordPress posts.
*
* @package WPDiscourse\SyncDiscourseTopic
* @todo Review phpcs disablement.
*/
// phpcs:disable WordPress.DB.PreparedSQL
namespace WPDiscourse\SyncDiscourseTopic;
use WPDiscourse\DiscourseBase;
use WPDiscourse\Shared\WebhookUtilities;
/**
* Class SyncDiscourseTopic
*/
class SyncDiscourseTopic extends DiscourseBase {
use WebhookUtilities;
/**
* The current version of the wpdc_topic_blog database table.
*
* @access protected
* @var string
*/
protected $db_version = '1.0';
/**
* Logger context
*
* @access protected
* @var string
*/
protected $logger_context = 'webhook_topic';
/**
* SyncDiscourseTopic constructor.
*/
public function __construct() {
add_action( 'init', array( $this, 'setup_options' ) );
add_action( 'init', array( $this, 'setup_logger' ) );
add_action( 'rest_api_init', array( $this, 'initialize_update_content_route' ) );
add_action( 'plugins_loaded', array( $this, 'maybe_create_db' ) );
$this->supported_events = array(
'post_created',
'post_updated',
);
}
/**
* Registers the Rest API route wp-discourse/v1/update-topic-content.
*/
public function initialize_update_content_route() {
if ( $this->webhook_enabled() ) {
register_rest_route(
'wp-discourse/v1',
'update-topic-content',
array(
array(
'methods' => \WP_REST_Server::CREATABLE,
'permission_callback' => function () {
return true;
},
'callback' => array( $this, 'update_topic_content' ),
),
)
);
}
}
/**
* Handles the REST request.
*
* @param \WP_REST_Request $request The WP_REST_Request data object.
*
* @return null|\WP_Error
*/
public function update_topic_content( $request ) {
$data = $this->get_webhook_data( $request );
if ( is_wp_error( $data ) ) {
return $this->failed_response( $data->get_error_message() );
}
do_action( 'wpdc_before_webhook_post_update', $data->json );
$post_data = $data->json['post'];
$use_multisite_configuration = is_multisite() && ! empty( $this->options['multisite-configuration-enabled'] );
$post_ids = array();
if ( $use_multisite_configuration ) {
global $wpdb;
$table_name = $wpdb->base_prefix . 'wpdc_topic_blog';
$topic_id = intval( $post_data['topic_id'] );
$query = "SELECT blog_id FROM $table_name WHERE topic_id = %d";
$blog_id = $wpdb->get_var( $wpdb->prepare( $query, $topic_id ) );
if ( $blog_id ) {
switch_to_blog( $blog_id );
$post_ids = $this->update_post_metadata( $post_data );
restore_current_blog();
}
} else {
$post_ids = $this->update_post_metadata( $post_data );
}
do_action( 'wpdc_after_webhook_post_update', $post_ids );
if ( ! empty( $post_ids ) ) {
return $this->success_response( 'The posts have been updated.' );
} else {
return $this->failed_response( 'No posts were found.' );
}
}
/**
* Creates the wpdc_topic_blog database table using the site's base table prefix.
*
* The database table is only created in multisite installations when the multisite_configuration option is enabled.
* The table is used to associate the topic_id that's returned from a Discourse webhook request, with a post that's
* been published on a WordPress subsite.
*/
public function maybe_create_db() {
global $wpdb;
if ( is_multisite() ) {
$use_multisite_configuration = ( 1 === intval( get_site_option( 'wpdc_multisite_configuration' ) ) );
$create_or_update_db = get_site_option( 'wpdc_topic_blog_db_version' ) !== $this->db_version;
if ( $use_multisite_configuration && $create_or_update_db ) {
$table_name = $wpdb->base_prefix . 'wpdc_topic_blog';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
topic_id mediumint(9) NOT NULL,
blog_id mediumint(9) NOT NULL,
PRIMARY KEY (topic_id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$result = dbDelta( $sql );
if ( ! empty( $result[ $table_name ] ) ) {
update_site_option( 'wpdc_topic_blog_db_version', $this->db_version );
}
}
}
}
/**
* Tries to update some post metadata for WordPress posts that are associated with Discourse topics.
*
* The function tries to find the post from the Discourse topic_id that's returned with the webhook. For posts that
* have been published through the WP Discourse plugin prior to version 1.4.0 the topic_id will not be present. In
* this case, it then tries to find the post from its title. If that fails, an optional email notification is sent.
*
* If a post is found, if the post_number - 1 is greater than the saved discourse_comments_count, the comments count
* is updated and the post is marked as needing to be refreshed for the next time DiscourseComment::sync_comments is run.
*
* @param array $post_data The post_data from the Discourse webhook request.
* @return null
*/
protected function update_post_metadata( $post_data ) {
$topic_id = ! empty( $post_data['topic_id'] ) ? intval( $post_data['topic_id'] ) : null;
$post_number = ! empty( $post_data['post_number'] ) ? intval( $post_data['post_number'] ) : null;
$post_title = ! empty( $post_data['topic_title'] ) ? sanitize_text_field( $post_data['topic_title'] ) : null;
$comments_count = ! empty( $post_data['topic_posts_count'] ) ? intval( $post_data['topic_posts_count'] ) - 1 : null;
$post_type = ! empty( $post_data['post_type'] ) ? intval( $post_data['post_type'] ) : null;
$post_ids = array();
if ( $topic_id && $post_number && $post_title ) {
$post_ids = $this->get_post_ids_from_topic_id( $topic_id );
// For matching posts that were published before the plugin was saving the discourse_topic_id as post_metadata.
if ( ! $post_ids && ! empty( $this->options['webhook-match-old-topics'] ) ) {
$post_id = $this->get_post_id_by_title( $post_title, $topic_id );
if ( $post_id ) {
$post_ids[] = $post_id;
}
}
if ( $post_ids ) {
foreach ( $post_ids as $post_id ) {
update_post_meta( $post_id, 'wpdc_sync_post_comments', 1 );
// The topic_posts_count is being returned with the webhook data as of Discourse version 2.0.0.beta1.
if ( $comments_count ) {
update_post_meta( $post_id, 'discourse_comments_count', $comments_count );
} else {
// If the post_number is > discourse_comments_count, update the comments count.
$current_comment_count = get_post_meta( $post_id, 'discourse_comments_count', true );
if ( $current_comment_count < $post_number - 1 ) {
update_post_meta( $post_id, 'discourse_comments_count', $post_number - 1 );
}
}
$unlisted = get_post_meta( $post_id, 'wpdc_unlisted_topic', true );
if ( ! empty( $unlisted ) && $comments_count > 0 && 1 === $post_type ) {
$this->list_topic( $post_id, $topic_id );
}
}
if ( ! empty( $this->options['verbose-webhook-logs'] ) ) {
$this->logger->info( 'update_topic_content.update_post_metadata_success', array( 'post_ids' => implode( ',', $post_ids ) ) );
}
}
}
return $post_ids;
}
/**
* Changes a post's Discourse topic status from unlisted to listed.
*
* @param int $post_id The id of the post that needs to be listed.
* @param int $topic_id The id of the topic that needs to be listed.
*
* @return null|\WP_Error
*/
protected function list_topic( $post_id, $topic_id ) {
$status_path = "/t/{$topic_id}/status";
$body = array(
'status' => 'visible',
'enabled' => 'true',
);
$args = array(
'body' => $body,
'method' => 'PUT',
);
$response = $this->discourse_request( $status_url, $args );
if ( is_wp_error( $response ) ) {
return $response;
} elseif ( ! $this->validate( $response ) ) {
return new \WP_Error( 'discourse_response_error', 'Unable to unlist the Discourse topic.' );
}
delete_post_meta( $post_id, 'wpdc_unlisted_topic' );
return null;
}
/**
* Tries to match a WordPress post with a Discourse topic by the topic title.
*
* This function is used to match posts that have been published through the WP Discourse plugin prior to version 1.4.0
* with their associated Discourse topics. It assumes that the posts are using the 'post' type. There is a filter
* available to change the post type. There's also an action that can be hooked into if you'd like to try to match
* more than one post type.
*
* @param string $title The topic_title returned from Discourse.
* @param int $topic_id The topic_id returned from Discourse.
*
* @return int|null
*/
protected function get_post_id_by_title( $title, $topic_id ) {
$id = null;
$title = strtolower( $title );
$post_type = apply_filters( 'wpdc_webhook_get_page_by_title_post_type', 'post' );
$post = get_page_by_title( $title, 'OBJECT', $post_type );
if ( $post && ! is_wp_error( $post ) ) {
$id = $post->ID;
// Update the 'discourse_topic_id' metadata so that it can be used on the next webhook request.
update_post_meta( $id, 'discourse_topic_id', $topic_id );
}
do_action( 'wpdc_webhook_after_get_page_by_title', $title );
return $id;
}
/**
* Tries to find a WordPress posts that are associated with a Discourse topic_id.
*
* An array is being returned because it's possible for more than one WordPress post to be associated with a Discourse topic.
*
* @param int $topic_id The topic_id to lookup.
*
* @return array|null
*/
protected function get_post_ids_from_topic_id( $topic_id ) {
global $wpdb;
$topic_posts = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'discourse_topic_id' AND meta_value = %d", $topic_id ) );
if ( ! empty( $topic_posts ) ) {
$topic_post_ids = array();
foreach ( $topic_posts as $topic_post ) {
$topic_post_ids[] = $topic_post->post_id;
}
return $topic_post_ids;
}
return null;
}
/**
* Common webhook enabled function.
*/
protected function webhook_enabled() {
return ! empty( $this->options['use-discourse-webhook'] );
}
}