forked from mAAdhaTTah/wordpress-github-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordpress-github-sync.php
More file actions
314 lines (251 loc) · 8.9 KB
/
Copy pathwordpress-github-sync.php
File metadata and controls
314 lines (251 loc) · 8.9 KB
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
309
310
311
312
313
314
<?php
/**
* Plugin Name: WordPress GitHub Sync
* Plugin URI: https://github.com/benbalter/wordpress-github-sync
* Description: A WordPress plugin to sync content with a GitHub repository (or Jekyll site)
* Version: 0.0.1
* Author: Ben Balter
* Author URI: http://ben.balter.com
* License: GPLv2
* Domain Path: /languages
* Text Domain: wordpress-github-sync
*/
/* Copyright 2014 Ben Balter (email : ben@balter.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
require_once dirname( __FILE__ ) . '/vendor/autoload.php';
class WordPress_GitHub_Sync {
static $instance;
static $text_domain = "wordpress-github-sync";
static $version = "0.0.1";
public $push_lock = false;
/**
* Called at load time, hooks into WP core
*/
function __construct() {
self::$instance = &$this;
add_action( 'init', array( &$this, 'l10n' ) );
add_action( 'save_post', array( &$this, 'save_post_callback' ) );
add_action( 'delete_post', array( &$this, 'delete_post_callback' ) );
add_action( 'wp_ajax_nopriv_wpghs_sync_request', array( &$this, 'pull_posts' ));
add_action( 'wpghs_export', array( &$this, 'export_posts' ));
add_action( 'init', array( &$this, 'continue_export' ) );
if (is_admin()) {
$this->admin = new WordPress_GitHub_Sync_Admin;
}
}
/**
* Init i18n files
*/
function l10n() {
load_plugin_textdomain( self::$text_domain, false, plugin_basename( dirname( __FILE__ ) ) . '/languages/' );
}
/**
* Returns the repository to sync with
*/
function repository() {
return get_option( "wpghs_repository" );
}
/**
* Returns the user's oauth token
*/
function oauth_token() {
return get_option( "wpghs_oauth_token" );
}
/**
* Returns the GitHub host to sync with (for GitHub Enterprise support)
*/
function api_base() {
return get_option( "wpghs_host" );
}
/**
* Returns the Webhook secret
*/
function secret() {
return get_option( "wpghs_secret" );
}
/**
* Callback triggered on post save, used to initiate an outbound sync
*
* $post_id - (int) the post to sync
*/
function save_post_callback($post_id) {
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) )
return;
if ( ! $this->oauth_token() || ! $this->repository() )
return
$post = get_post($post_id);
// Right now CPTs are not supported
if ($post->post_type != "page" && $post->post_type != "post")
return;
// Not yet published
if ($post->post_status != "publish")
return;
$post = new WordPress_GitHub_Sync_Post($post_id);
$post->push();
}
/**
* Callback triggered on post delete, used to initiate an outbound sync
*
* $post_id - (int) the post to delete
*/
function delete_post_callback( $post_id ) {
if ( ! $this->oauth_token() || ! $this->repository() )
return
$post = get_post($post_id);
// Right now CPTs are not supported
if ($post->post_type != "page" && $post->post_type != "post")
return;
$post = new WordPress_GitHub_Sync_Post($post_id);
$post->delete();
}
/**
* Webhook callback as trigered from GitHub push
* Reads the payload and syncs posts as necessary
*/
function pull_posts() {
# Prevent pushes on update
$this->push_lock = true;
$raw_data = file_get_contents('php://input');
$headers = $this->headers();
// validate secret
$hash = hash_hmac( "sha1", $raw_data, $this->secret() );
if ( $headers["X-Hub-Signature"] != "sha1=" . $hash )
wp_die( __("Failed to validate secret.", WordPress_GitHub_Sync::$text_domain) );
$data = json_decode($raw_data);
$nwo = $data->repository->owner->name . "/" . $data->repository->name;
if ( $nwo != $this->repository() )
wp_die( $nwo . __(" is an invalid repository", WordPress_GitHub_Sync::$text_domain) );
$modified = $added = $removed = array();
foreach ($data->commits as $commit) {
$modified = array_merge( $modified, $commit->modified );
$added = array_merge( $added, $commit->added );
$removed = array_merge( $removed, $commit->removed );
}
// Added or Modified (pull)
$to_pull = array_merge($modified, $added);
foreach (array_unique($to_pull) as $path) {
$post = new WordPress_GitHub_Sync_Post($path);
$post->pull();
}
// Removed
foreach (array_unique($removed) as $path) {
$post = new WordPress_GitHub_Sync_Post($path);
wp_delete_post($post->id);
}
}
/**
* Cross-server header support
* Returns an array of the request's headers
*/
function headers() {
if (function_exists('getallheaders'))
return getallheaders();
// Nginx and pre 5.4 workaround
// http://www.php.net/manual/en/function.getallheaders.php
$headers = array();
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
/**
* Get posts to export, set and kick off cronjob
*/
function start_export() {
global $wpdb;
$posts = get_option( '_wpghs_posts_to_export' );
if ( ! $posts ) {
$posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ('post', 'page' )" );
} else {
delete_option( '_wpghs_posts_to_export' );
}
wp_schedule_single_event(time(), 'wpghs_export', array($posts));
$this->log( __("Starting export to GitHub", WordPress_GitHub_Sync::$text_domain ) );
spawn_cron();
update_option( '_wpghs_export_started', 'yes' );
}
/**
* Export posts
*
* Runs as cronjob
*/
function export_posts($posts) {
$i = 0;
while(!empty($posts) && $i < 50) {
$post_id = array_shift($posts);
$this->log( __("Exporting Post ID: ", WordPress_GitHub_Sync::$text_domain ) . $post_id );
$post = new WordPress_GitHub_Sync_Post($post_id);
$result = $post->push();
if ( is_wp_error( $result ) ) {
update_option( '_wpghs_posts_to_export', $posts );
update_option( '_wpghs_export_error', $result->get_error_message() );
$this->log( __("Error exporting to GitHub. Error:", WordPress_GitHub_Sync::$text_domain ) );
$this->log( $result->get_error_message() );
die();
}
usleep(500000);
$i++;
}
if (!empty($posts)) {
$nonce = wp_hash( time() );
update_option( '_wpghs_export_nonce', $nonce );
// Request page that will continue export
wp_remote_post( add_query_arg( 'github', 'sync', site_url( 'index.php' ) ), array(
'body' => array(
'posts' => $posts,
'nonce' => $nonce,
),
'blocking' => false,
) );
} else {
update_option( '_wpghs_export_complete', 'yes' );
$this->log( __('Export to GitHub completed successfully.', WordPress_GitHub_Sync::$text_domain ) );
}
die();
}
/**
* Receives the remaining posts
*
* Kicks off exporting the next batch
*/
function continue_export() {
if ( ! isset( $_GET['github'] ) || 'sync' !== $_GET['github'] ) {
return;
}
if ( !array_key_exists('nonce', $_POST) || "" === get_option( '_wpghs_export_nonce') || get_option( '_wpghs_export_nonce') !== $_POST['nonce'] ) {
return;
}
delete_option( '_wpghs_export_nonce' );
if ( !array_key_exists('posts', $_POST) || !is_array($_POST['posts']) ) {
return;
}
$posts = $_POST['posts'];
$this->export_posts($posts);
}
/**
* Write to debug.log if WP_DEBUG is enabled
* @source http://www.stumiller.me/sending-output-to-the-wordpress-debug-log/
*/
function log($log) {
if ( true === WP_DEBUG ) {
if ( is_array( $log ) || is_object( $log ) ) {
error_log( print_r( $log, true ) );
} else {
error_log( $log );
}
}
}
}
$wpghs = new WordPress_GitHub_Sync;