Repository navigation
Expand file tree
/
Copy pathclient-save-playground.php
More file actions
383 lines (331 loc) · 16.7 KB
/
Copy pathclient-save-playground.php
File metadata and controls
383 lines (331 loc) · 16.7 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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
<?php
function qckply_clear_sync_token() {
delete_option('qckply_sync_token');
delete_option('qckply_sync_token_expires');
}
function qckply_get_sync_token($force_refresh = false) {
$sync_code = get_option('qckply_sync_code');
$sync_origin = get_option('qckply_sync_origin');
$profile = get_option('qckply_profile', 'default');
$token = get_option('qckply_sync_token', '');
$expires = intval(get_option('qckply_sync_token_expires', 0));
if(!$force_refresh && !empty($token) && $expires > (time() + MINUTE_IN_SECONDS)) {
return $token;
}
if(empty($sync_code) || empty($sync_origin) || empty($profile)) {
qckply_clear_sync_token();
return '';
}
$response = wp_remote_post(
$sync_origin.'/wp-json/quickplayground/v1/authorize_sync/'.$profile,
[
'body' => wp_json_encode(['sync_code' => $sync_code]),
'headers' => ['Content-Type' => 'application/json'],
'timeout' => 20,
]
);
if(is_wp_error($response)) {
qckply_clear_sync_token();
return '';
}
if(200 !== wp_remote_retrieve_response_code($response)) {
qckply_clear_sync_token();
return '';
}
$payload = json_decode(wp_remote_retrieve_body($response), true);
if(empty($payload['sync_token']) || empty($payload['expires'])) {
qckply_clear_sync_token();
return '';
}
update_option('qckply_sync_token', sanitize_text_field($payload['sync_token']));
update_option('qckply_sync_token_expires', intval($payload['expires']));
return sanitize_text_field($payload['sync_token']);
}
function qckply_prepare_sync_payload($payload, $force_refresh = false) {
$sync_token = qckply_get_sync_token($force_refresh);
if(empty($sync_token)) {
return false;
}
if(!is_array($payload)) {
$payload = [];
}
unset($payload['sync_code']);
$payload['sync_token'] = $sync_token;
return $payload;
}
function qckply_sync_remote_post($url, $payload) {
$prepared = qckply_prepare_sync_payload($payload);
if(false === $prepared) {
return new WP_Error('qckply_sync_token_missing', __('Unable to authorize Quick Playground sync.', 'quick-playground'));
}
$body = qckply_json_outgoing(wp_json_encode($prepared));
$response = wp_remote_post($url, [
'body' => $body,
'headers' => ['Content-Type' => 'application/json'],
]);
$status_code = wp_remote_retrieve_response_code($response);
if(!is_wp_error($response) && in_array($status_code, [401, 403], true)) {
$prepared = qckply_prepare_sync_payload($payload, true);
if(false !== $prepared) {
$body = qckply_json_outgoing(wp_json_encode($prepared));
$response = wp_remote_post($url, [
'body' => $body,
'headers' => ['Content-Type' => 'application/json'],
]);
}
}
return $response;
}
function qckply_clone_save_playground($clone) {
global $wpdb;
$profile = get_option("qckply_profile",'default');
printf('<h2>Saving Playground Data for %s</h2>',esc_html($profile));
$sync_origin = get_option('qckply_sync_origin');
$site_dir = '/wp-content/uploads'.get_option('qckply_site_dir');
$qckply_mysite_url = site_url();
$origin_stylesheet = get_option('origin_stylesheet');
$save_posts_url = $sync_origin.'/wp-json/quickplayground/v1/save_posts/'.$profile;
$save_settings_url = $sync_origin.'/wp-json/quickplayground/v1/save_settings/'.$profile;
$save_meta_url = $sync_origin.'/wp-json/quickplayground/v1/save_meta/'.$profile;
$save_custom_url = $sync_origin.'/wp-json/quickplayground/v1/save_custom/'.$profile;
$save_prompts_url = $sync_origin.'/wp-json/quickplayground/v1/save_prompts/'.$profile;
$post_ids = [];
$local_directories = qckply_get_directories();
$remote_directories = get_option('qckply_origin_directories');
if(!empty($clone['posts']))
{
$clone = qckply_posts_related($clone, true);
$json = json_encode($clone);
if(!$json) {
foreach($clone['posts'] as $index => $p) {
$p = (array) $p;
if(in_array($p['ID'],$post_ids))
continue;
$post_ids[] = $p['ID'];
$fix = false;
foreach($p as $field => $value) {
printf('<p>check %s encoding post content ID %d title %s value %s</p>',esc_html($field),esc_html($p['ID']),esc_html($p['post_title']),esc_html(substr($value,0,50)));
$clean = wp_check_invalid_utf8( $value );
if($clean !== $value) {
$fix = true;
$p[$field] = $clean;
printf('<p>fix %s encoding post content ID %d title %s</p>',esc_html($field),esc_html($p['ID']),esc_html($p['post_title']));
}
}
if($fix) {
$clone['posts'][$index] = (object) $p;
}
}
$json = json_encode($clone);
}
if(!$json) {
echo '<p>Error encoding JSON: '.esc_html(json_last_error_msg()).'</p>';
}
else
printf('<h3>Save %d Posts and %s Related Items</h3><p>Sample JSON: %s</p>',empty($clone['posts']) ? 0 : sizeof($clone['posts']),empty($clone['related']) ? 0 : sizeof($clone['related']),esc_html(substr($json,0,300)));
$payload = json_decode($json, true);
$response = qckply_sync_remote_post($save_posts_url, $payload);
$status_code = wp_remote_retrieve_response_code( $response );
if(is_wp_error($response)) {
echo '<p>Error: '.esc_html( htmlentities($response->get_error_message()) ).'</p>';
}
elseif(200 != $status_code) {
echo '<p>Error: HTTP status code '.esc_html( $status_code ).'</p>';
if(!empty($returned['message']))
printf('<p>%s</p>',esc_html('Server message: '.$returned['message']));
printf('<div class="notice notice-error"><p>Error saving over the network. A security plugin such as WordFence could be blocking the connection. <a href="%s">Retry</a> or try <a href="%s">downloading</a> instead.</p></div>',esc_attr(admin_url('admin.php?page=qckply_save')),esc_attr(rest_url('quickplayground/v1/download_json/'.$profile)));
printf('<p><a href="%s">Retry</a></p>',esc_attr(admin_url('admin.php?page=qckply_save')));
echo '<p>If you see this repeatedly, please report the issue via <a href="https://wordpress.org/support/plugin/quick-playground/">https://wordpress.org/support/plugin/quick-playground/</a></p>';
$file = 'quickplayground_posts_'.$profile.'.json';
$filename = trailingslashit($local_directories['site_uploads']).$file;
file_put_contents($filename, qckply_json_outgoing(wp_json_encode($payload)));
return;
}
else {
$returned = $response['body'];
if(!is_array($returned)) {
$returned = json_decode($returned, true);
}
if(!is_array($returned)) {
echo 'not an array: '.esc_html(var_export($returned,true));
}
if(!empty($returned['saved']))
printf('<p>Saved %s bytes of post content to %s</p>',esc_html($returned['saved']),esc_html($returned['file']));
if(!empty($returned['message']))
printf('<p>%s</p>',esc_html('Server message: '.$returned['message']));
}
}
$clone = [];
$clone['settings']['cache_created'] = time();
$updated_options = get_option('qckply_updated_options',[]);
if(!in_array('stylesheet',$updated_options))
$updated_options[] = 'stylesheet';//always include stylesheet
foreach($updated_options as $option) {
if('qckply_sync_code' == $option)
continue;
$v = get_option($option);
$clone['settings'][$option] = $v;
}
$clone = apply_filters('qckply_clone_save_settings',$clone);
printf('<h3>Saving %d Settings</h3>',esc_html(sizeof($clone['settings'])));
$response = qckply_sync_remote_post($save_settings_url, $clone);
if(is_wp_error($response)) {
echo '<p>Error: '.esc_html( htmlentities($response->get_error_message()) ).'</p>';
return;
} else {
$returned = $response['body'];
if(!is_array($returned)) {
$returned = json_decode($returned, true);
}
if(!is_array($returned)) {
echo 'not an array: '.esc_html(var_export($returned,true));
}
if(!empty($returned['saved']))
printf('<p>Saved %s bytes of settings to %s %s</p>',esc_html($returned['saved']),esc_html($returned['file']),($returned['saved'] < 10) ? '(probable error)' : '');
if(!empty($returned['message']))
printf('<p>%s</p>',esc_html($returned['message']));
}
/*
$clone = [];
$clone['related'] = qckply_posts_related($post_ids);
$clone['postmeta'] = $wpdb->get_results("SELECT * FROM $wpdb->postmeta");
$clone['users'] = $wpdb->get_results("SELECT * FROM $wpdb->users");
$clone['usermeta'] = $wpdb->get_results("SELECT * FROM $wpdb->usermeta");
$clone = apply_filters('qckply_clone_save_meta',$clone);
$clone = qckply_json_outgoing(json_encode($clone),$sync_origin.$site_dir);
echo '<h3>Saving Meta and Taxonomy Data</h3>';
$response = wp_remote_post($save_meta_url, array(
'body' => $clone,
'headers' => array('Content-Type' => 'application/json')
));
if(is_wp_error($response)) {
echo '<p>Error: '.esc_html( htmlentities($response->get_error_message()) ).'</p>';
} else {
$returned = $response['body'];
if(!is_array($returned)) {
$returned = json_decode($returned, true);
}
if(!is_array($returned)) {
echo 'not an array: '.esc_html( var_export($returned,true) );
}
if(!empty($returned['saved']))
printf('<p>Saved %s bytes of metadata</p>',esc_html($returned['saved']));
if(!empty($returned['message']))
printf('<p>%s</p>',esc_html($returned['message']));
}
*/
$clone = qckply_custom_tables_clone([]);
printf('<h3>Checking for Custom Table Data</h3><p>%s</p>',esc_html( var_export(!empty($clone['custom_tables']),true)) );
if(!empty($clone['custom_tables']))
{
echo '<h3>Saving Custom Table Data</h3>';
$response = qckply_sync_remote_post($save_custom_url, $clone);
if(is_wp_error($response)) {
echo '<p>Error: '.esc_html( htmlentities($response->get_error_message()) ).'</p>';
} else {
$returned = $response['body'];
if(!is_array($returned)) {
$returned = json_decode($returned, true);
}
if(!is_array($returned)) {
echo 'not an array: '.esc_html(var_export($returned,true));
}
if(!empty($returned['saved']))
printf('<p>Saved %s bytes to %s %s</p>',esc_html($returned['saved']),esc_html($returned['file']),($returned['saved'] < 10) ? '(probable error)' : '');
if(!empty($returned['message']))
printf('<p>%s</p>',esc_html($returned['message']));
}
}
printf('<h3 style="color: green; font-weight: bold;">Playground save complete %s</h3>',esc_html(date('r')) );
printf('<p><a href="%s" target="_blank">Save to Live Website</a> - administrator approval required on %s.</p>',esc_attr($sync_origin.'/wp-admin/admin.php?page=qckply_sync'),esc_html($sync_origin));
}
function qckply_posts() {
global $wpdb;
$qckply_mysite_url = site_url();
$top = qckply_top_ids();
$sync_origin = get_option('qckply_sync_origin');
$site_dir = '/wp-content/uploads'.get_option('qckply_site_dir');
$search_path = $qckply_mysite_url.'/wp-content/uploads';
$replace_path = $sync_origin.$site_dir;
//block theme assets first
$sql = $wpdb->prepare("SELECT * FROM %i WHERE post_status='publish' AND (post_type = 'wp_template' OR post_type = 'wp_template_part' OR post_type = 'wp_global_styles' OR post_type='wp_navigation' ) AND post_modified > %s ORDER BY post_modified DESC",$wpdb->posts, $top['post_modified']);
$templates = $wpdb->get_results($sql);
//then other posts
$sql = $wpdb->prepare("SELECT * FROM %i WHERE post_status='publish' AND post_type != 'attachment' AND post_type != 'wp_template' AND post_type != 'wp_template_part' AND post_type != 'wp_global_styles' AND post_type!='wp_navigation' AND post_modified > %s ORDER BY post_modified DESC",$wpdb->posts, $top['post_modified']);
$posts = $wpdb->get_results($sql);
if(empty($posts))
$posts = [];
if(!empty($templates))
$posts = array_merge($templates,$posts); // templates first, then any regular content
printf('<p>Found %d posts modified since last sync with %s</p>',esc_html(count($posts)),esc_html($sql));
$ids = [];
foreach($posts as $index => $post) {
printf('<p>ID %s %s (%s) %s</p>',esc_html($post->ID),esc_html($post->post_title),esc_html($post->post_type),esc_html($post->post_modified));
$ids[] = $post->ID;
}
return ['posts'=>$posts,'ids'=>$ids];
}
function qckply_sync_code_form($form) {
$action = admin_url('admin.php?page='.$form);
$profile = get_option("qckply_profile",'default');
$qckply_home_link = get_option('qckply_dashboard_home');
if(empty($_POST['qckply_sync_code'])) {
printf('<form method="post" action="%s">',esc_attr($action));
wp_nonce_field( 'quickplayground', 'playground' );
printf(__('<p>First, please enter the Sync Code from the <a target="_blank" href="%s">Quick Playground screen</a> on the dashboard of your live website. This is necessary to save your changes and potentially implement them on your live site.</p>','quick-playground'),$qckply_home_link);
printf('<p><label for="qckply_sync_code">%s</label> <input type="text" name="qckply_sync_code" id="qckply_sync_code" value="" size="40" /></p>',esc_html__('Sync Code:','quick-playground'));
printf('<p><input type="submit" class="button button-primary" value="%s" /></p>',esc_html__('Submit Sync Code','quick-playground'));
echo '</form>';
return '';
} else {
if(!wp_verify_nonce( sanitize_text_field( wp_unslash ( $_POST['playground'])), 'quickplayground' ) )
{
echo '<h2>'.esc_html__('Security Error','quick-playground').'</h2>';
return '';
}
$qckply_sync_code = sanitize_text_field( wp_unslash ( $_POST['qckply_sync_code'] ) );
update_option('qckply_sync_code',$qckply_sync_code);
qckply_clear_sync_token();
printf(__('<p>Sync Code %s saved. <a href="%s">Reload page</a>.</p>', 'quick-playground'), esc_html($qckply_sync_code), esc_attr($action));
}
}
function qckply_save() {
global $wpdb;
printf('<h1>%s</h1><p>%s</p>',esc_html__('Save and Sync Playground','quick-playground'),esc_html__('You can save the current state of the Playground for future sessions or to sync to your live website.','quick-playground'));
$qckply_sync_code = get_option('qckply_sync_code');
if(empty($qckply_sync_code)) {
qckply_sync_code_form('qckply_save');
return;
}
$sync_origin = $qckply_baseurl = get_option('qckply_sync_origin');
$qckply_profile = get_option('qckply_profile','default');
printf('<p><a href="%s" target="_blank">Save to Live Website</a> - administrator approval required on %s.</p>',esc_attr($sync_origin.'/wp-admin/admin.php?page=qckply_sync&profile='.$qckply_profile),esc_html($sync_origin));
if(!empty($_POST) && !wp_verify_nonce( sanitize_text_field( wp_unslash ( $_POST['playground'])), 'quickplayground' ) )
{
echo '<h2>'.esc_html__('Security Error','quick-playground').'</h2>';
return;
}
qckply_upload_images_form();
if(!empty($_POST))
return;
$origin_stylesheet = get_option('origin_stylesheet');
$no_cache = get_option('qckply_no_cache',false);
$qckply_profile = get_option('qckply_profile','default');
$url = $qckply_baseurl .'/wp-json/quickplayground/v1/clone_posts/'.$qckply_profile.'?t='.time();
if($no_cache) $url .= '&nocache=1';
$taxurl = $qckply_baseurl .'/wp-json/quickplayground/v1/clone_taxonomy/'.$qckply_profile.'?t='.time();
if($no_cache) $taxurl .= '&nocache=1';
$imgurl = $qckply_baseurl .'/wp-json/quickplayground/v1/clone_images/'.$qckply_profile.'?t='.time();
if($no_cache) $imgurl .= '&nocache=1';
$sync_date = get_option('qckply_sync_date');
$action = admin_url('admin.php?page=qckply_save');
if(empty(qckply_get_sync_token())) {
echo '<div class="notice notice-error"><p>'.esc_html__('Unable to authorize sync with the live website. Re-enter the sync code and try again.', 'quick-playground').'</p></div>';
qckply_clear_sync_token();
return;
}
$clone = qckply_posts();
error_log('play_posts '.sizeof($clone['posts']));
qckply_clone_save_playground($clone);
set_transient('qckply_messages_updated',false);
}