-
Notifications
You must be signed in to change notification settings - Fork 0
/
libpress_menu_mgmt.php
389 lines (343 loc) · 12.6 KB
/
libpress_menu_mgmt.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
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
383
384
385
386
387
388
389
<?php
/**
* LibPress Menu Management
*
* Adds functionality for network-wide exporting for backup
*
* PHP Version 7
*
* @package BCLibCoop\MenuMgmt
* @author Jonathan Schatz <jonathan.schatz@bc.libraries.coop>
* @author Sam Edwards <sam.edwards@bc.libraries.coop>
* @copyright 2020-2022 BC Libraries Cooperative
* @license GPL-2.0-or-later
*
* @wordpress-plugin
* Plugin Name: LibPress Menu Management
* Description: Adds functionality for network-wide exporting for backup
* Version: 3.0.0
* Network: true
* Requires at least: 5.2
* Requires PHP: 7.0
* Author: BC Libraries Cooperative
* Author URI: https://bc.libraries.coop
* Text Domain: libpress-menu-mgmt
* License: GPL v2 or later
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt
*/
/**
* -------------------
* CLI Command section
* -------------------
*/
/**
* Define export directory constant
*/
defined('MENU_MGMT_EXPORT_DIR') or define('MENU_MGMT_EXPORT_DIR', '/home/siteuser/libpress_menu_backups/');
/**
* Custom CLI commands
*/
if (defined('WP_CLI') && WP_CLI) {
WP_CLI::add_command('libpress-export-blogmenus', 'libpress_menu_mgmt_export_blog_menu');
WP_CLI::add_command('libpress-import-blogmenu', 'libpress_menu_mgmt_import_blog_menu');
}
/**
* Backup a given blog's menu structure.
*
* @param array $args
* @param array $assoc_args
*
* Usage: `wp libpress-export-blog-menus --id=123`
*/
function libpress_menu_mgmt_export_blog_menu($args = [], $assoc_args = [])
{
// Get arguments.
$arguments = wp_parse_args(
$assoc_args,
[
'blogid' => 1,
'network' => false
]
);
if ($arguments['network'] == true) {
// ignore blogid, loop through all blog sites
$sites = get_sites([
'public' => 1,
'archived' => 0,
'deleted' => 0,
]);
foreach ($sites as $site) {
libpress_export_runner($site);
}
} else {
$blog_id = (int) $arguments['blogid'];
WP_CLI::debug("Using blogid: {$blog_id}");
// blogid defaults to 1 but could be set to non-numeric or null
if ($blog_id > 0 && $arguments['network'] == false) {
// Load the $blog object from blogid
if ($blog = get_blog_details($blog_id)) {
libpress_export_runner($blog);
} else {
WP_CLI::warning('Invalid blog id.');
}
} else {
WP_CLI::warning('Could not complete network run due to bad arguments.');
}
}
}
/**
* Runs the export command with canned params given a WP_Site object
*
* @param \WP_Site $blog
*/
function libpress_export_runner($blog)
{
//Setup
$timestamp = date("Ymd_His");
$dir = MENU_MGMT_EXPORT_DIR . $blog->domain . '/';
$command = "export --url=$blog->siteurl --dir=$dir --post_type=nav_menu_item --skip_comments=TRUE --filename_format='menu_backup.$timestamp.xml'";
$options = array();
// @todo add cronjob to ensure only last 3 exist in each dir
if (!is_dir($dir)) {
mkdir($dir, 0774, true);
}
//Run composed export command
try {
WP_CLI::debug("Ran command" . $command);
WP_CLI::runcommand($command, $options);
// Show success message.
WP_CLI::success("Menus for blogID: $blog->blogname ($blog->blog_id) successfully.");
return true;
} catch (Exception $e) {
// Arguments not okay, show an error.
WP_CLI::error("Failed with $e->getMessage(). Check the value given for blogID ($blog->blog_id).");
}
}
/**
* The CLI import command. Will delete existing menus, import from the file
* specified, then assign the imported menus to the correct menu locations.
*
* @param string $filepath
*/
function libpress_menu_mgmt_import_blog_menu($filepath)
{
if (empty($filepath)) {
WP_CLI::error("Please specify a file to import");
}
if (!is_readable($filepath[0])) {
WP_CLI::error("Cannot read file for import: " . $filepath[0]);
}
$menu_locations = [
'main-menu' => 'primary',
'footer-menu' => 'secondary'
];
$xml = simplexml_load_file($filepath[0]);
if ($xml === false) {
WP_CLI::error("Could not parse export file");
}
$blog_url = reset($xml->channel->link);
if (!empty($blog_url)) {
// Ask
WP_CLI::confirm(WP_CLI::colorize("%mMain, footer menus for $blog_url will be deleted.%n Proceed?"));
try {
// Delete the existing menus first so we get a clean import.
// TODO: Rename and remove from location rather than delete?
foreach ($menu_locations as $menu => $location) {
WP_CLI::runcommand("menu delete $menu --url=$blog_url");
WP_CLI::line("Deleted existing menus.");
}
WP_CLI::runcommand("import $filepath[0] --authors=skip --url=$blog_url"); # No success call needed, has it's own.
foreach ($menu_locations as $menu => $location) {
WP_CLI::runcommand("menu location assign $menu $location --url=$blog_url");
WP_CLI::line("Assigned imported menus to their respective locations.");
}
} catch (Exception $e) {
WP_CLI::error("Failed to import with $e->getMessage().");
}
} else {
WP_CLI::error("Could not determine blog URL from file");
}
}
/**
* -------------------------
* Menu Change Watch Section
* -------------------------
* TODO: Make these actually do something. Can't just use the WPCLI functions
* as they won't work from a web context.
*/
/**
* Look for changes to the menu. This will catch anything from the `nav-menus.php`
* page, but not from the customizer.
*/
add_action('load-nav-menus.php', function () {
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : null;
$nav_menu_selected_id = isset($_REQUEST['menu']) ? (int) $_REQUEST['menu'] : 0;
$menu_item_id = isset($_REQUEST['menu-item']) ? (int) $_REQUEST['menu-item'] : 0;
if ($action && ($nav_menu_selected_id || $menu_item_id)) {
switch (WP_ENV) {
case 'production':
// TODO: Backup
break;
case 'staging':
// Don't Backup
break;
case 'development':
default:
// Log
error_log('Menus Changed');
}
}
});
/**
* Catch when menu changes are being published through the customizer
*/
add_action('customize_save', function ($customizer) {
$changeset_setting_ids = array_keys($customizer->unsanitized_post_values([
'exclude_post_data' => true,
'exclude_changeset' => false,
]));
if (!empty(preg_grep('/nav_menu/', $changeset_setting_ids))) {
switch (WP_ENV) {
case 'production':
// TODO: Backup
break;
case 'staging':
// Don't Backup
break;
case 'development':
default:
// Log
error_log('Menus Changed');
}
}
});
/**
* ---------------------
* Import Helper Section
* ---------------------
*
* The WP Importer wants all menu link destinations (terms/posts) to be included
* in the import file, since it's assuming this is a fresh import into a new site,
* but we're importing to the same site and assuming most/all IDs are the same.
* The following two hooks will fake the term/post data needed to make the
* importer happy.
*/
/**
* WP Importer term helper. Injects all current terms into the importer so they
* get added to its internal mapping array.
*/
add_filter('wp_import_terms', function ($terms) {
$all_nav_menu = true;
$fake_processed_terms = [];
foreach ($terms as $term) {
if ($term['term_taxonomy'] !== 'nav_menu') {
$all_nav_menu = false;
break;
}
}
if ($all_nav_menu) {
// We have no way to determine what terms/taxonomies might be in use
// by the menu. The only solution I can think of is to include all of them.
$all_terms = get_terms([
'get' => 'all',
]);
foreach ($all_terms as $all_term) {
// Only what's required for the importer mapping
$fake_processed_terms[] = [
'term_id' => $all_term->term_id,
'slug' => $all_term->slug,
'term_taxonomy' => $all_term->taxonomy,
];
}
$terms = array_merge($terms, $fake_processed_terms);
}
return $terms;
});
/**
* WP Importer post helper. Adds any post id referenced by a menu to the array
* of posts to be imported so they'll be added to the importer's internal mapping
* array.
*
* Tried to make this also add an invalid ID for targets that don't exist on the
* site anymore, but that didn't seem possible in a clean way, so only throwing
* HTML errors instead.
*/
add_filter('wp_import_posts', function ($posts) {
$all_nav_menu = true;
$fake_processed_posts = [];
foreach ($posts as $post) {
if ($post['post_type'] !== 'nav_menu_item') {
$all_nav_menu = false;
break;
}
}
if ($all_nav_menu) {
foreach ($posts as $item) {
// Set up postmeta as variables
foreach ($item['postmeta'] as $meta) {
${$meta['key']} = $meta['value'];
}
if ($_menu_item_type === 'post_type') {
$post_id = intval($_menu_item_object_id);
// Check if we've already inserted this post into the array
if (array_search($post_id, array_column($fake_processed_posts, 'post_id')) === false) {
// To make a long story short, if the post doesn't actually exist, then it's going
// to be a problem down the road, so only actually insert fake entries for posts
// that are still around.
if (get_post($post_id)) {
// If not, create the minimum post-like array needed to do what we need
$fake_processed_posts[] = [
// We'll check for this later
'menu_import_post' => true,
'status' => 'publish',
'post_id' => $post_id,
'post_type' => $_menu_item_object,
// By passing through no title or date, we can totally skip
// the DB check, saving some time
'post_title' => '',
'post_date' => '',
// Just set these as empty arrays to be safe
'terms' => [],
'comments' => [],
'postmeta' => [],
];
} else {
// TODO: Keep track of posts we've checked and aren't found
printf(
'Menu Item “%s” skipped due to nonexistent post ID %s',
esc_html($item['post_title']),
$post_id
);
echo '<br />';
}
}
} elseif ($_menu_item_type === 'taxonomy') {
// All known taxonomies added to the relevant matching array in the other helper,
// so this is only here to generate errors.
$check_term = get_term($_menu_item_object_id, $_menu_item_object);
if (!$check_term || is_wp_error($check_term)) {
printf(
'Menu Item “%s” skipped due to nonexistent term ID %s in taxonomy %s',
esc_html($item['post_title']),
$_menu_item_object_id,
$_menu_item_object
);
echo '<br />';
}
}
}
$posts = array_merge($posts, $fake_processed_posts);
}
return $posts;
});
/**
* When we detect a post that we manually inserted into the import array,
* simply return the ID that we set. We've already checked that the post exists
* in the DB, so this should be safe to do.
*/
add_filter('wp_import_existing_post', function ($post_exists, $post) {
if ($post_exists === 0 && isset($post['menu_import_post']) && $post['menu_import_post']) {
$post_exists = $post['post_id'];
}
return $post_exists;
}, 10, 2);