-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathps_wordpress.php
More file actions
353 lines (279 loc) · 13.2 KB
/
ps_wordpress.php
File metadata and controls
353 lines (279 loc) · 13.2 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
<?php
namespace Deployer;
use Deployer\Exception\GracefulShutdownException;
require __DIR__ . '/ps_base.php';
set('keep_releases', 5);
set('writable_mode', 'chmod');
set('remote_db_backup_path', '/container/backups/containers/latest/databases');
set('remote_assets_backup_path', '/container/backups/containers/latest/application/shared/public/assets');
set('deploy_path', '/container/application/theme');
set('identity_file', '~/.ssh/id_rsa');
set('shared_path', '/container/application/public');
set('sitehost_restart_mode', 'container');
set('sub_directory', 'wp-content/themes');
set('shared_dirs', []);
set('shared_files', []);
set('writable_dirs', []);
// ==================================================================
// Initial Preparation
/**
* Checks if wp-cli is installed on the remote server.
* If not found, downloads and installs it to ~/bin/wp.
*/
task('sitehost:wpcli', function () {
if (test('command -v wp')) {
writeln('<info>wp-cli is already installed: ' . run('wp --info --allow-root 2>&1 | head -1') . '</info>');
} else {
writeln('wp-cli not found — installing...');
run('mkdir -p ~/bin');
run('curl -sS -o ~/bin/wp https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar');
run('chmod +x ~/bin/wp');
run('echo "export PATH=\$HOME/bin:\$PATH" >> ~/.bashrc');
writeln('<info>wp-cli installed to ~/bin/wp</info>');
writeln('<comment>Note: You may need to reconnect or run `source ~/.bashrc` for `wp` to be available in PATH.</comment>');
}
});
/**
* Checks for an existing SSH key on the remote server.
* If none is found, generates a new RSA key and outputs the public key
* to be added as a deploy key on GitHub.
*/
task('sitehost:ssh', function () {
if (test('[ ! -f ~/.ssh/id_rsa ]')) {
writeln('Generating new ssh key');
run('ssh-keygen -f ~/.ssh/id_rsa -t rsa -N ""');
run('cat ~/.ssh/id_rsa.pub', ['real_time_output' => true]);
writeln('Copy this key to the projects deploy keys on github');
} else {
writeln('ssh key found - skipping');
run('cat ~/.ssh/id_rsa.pub', ['real_time_output' => true]);
writeln('Copy this key to the projects deploy keys on github');
}
});
/**
* Modifies wp-config.php on the remote server:
* - Comments out the WP_DEBUG definition.
* - Inserts a require_once for wp-config-env.php above the "stop editing" line.
*/
task('sitehost:config', function () {
$wpConfig = '/container/application/public/wp-config.php';
$wpConfigEnv = '/container/application/public/wp-config-env.php';
// Stage 1: Comment out WP_DEBUG
run("sed -i \"s|^define('WP_DEBUG', false);|// define('WP_DEBUG', false);|\" {$wpConfig}");
writeln('<info>WP_DEBUG line commented out in ' . $wpConfig . '</info>');
// Stage 2: Insert require_once above the "stop editing" line (only if not already present)
run("grep -qF \"require_once(ABSPATH . 'wp-config-env.php');\" {$wpConfig} || sed -i \"/\\/\\* That's all, stop editing! Happy blogging. \\*\\//i require_once(ABSPATH . 'wp-config-env.php');\" {$wpConfig}");
writeln('<info>require_once wp-config-env.php inserted in ' . $wpConfig . '</info>');
// Stage 3: Touch wp-config-env.php with <?php at the start (only if not already present)
run("[ -f {$wpConfigEnv} ] || echo '<?php' > {$wpConfigEnv}");
writeln('<info>wp-config-env.php created at ' . $wpConfigEnv . '</info>');
});
/**
* Runs initial server preparation steps: SSH key setup and wp-config modifications.
*/
task('sitehost:prepare', [
'sitehost:wpcli',
'sitehost:ssh',
'sitehost:config',
]);
// ==================================================================
// Ongoing Development
task('savefromremote', [
'savefromremote:db',
'savefromremote:assets'
]);
task('savefromremote:latest', [
'sitehost:backup',
'savefromremote:db',
'savefromremote:assets'
]);
task('sitehost:backup', function () {
if (testLocally('[ -f /var/www/sitehost-api-key.txt ]')) {
$config = file_get_contents('/var/www/sitehost-api-key.txt');
set('sitehost_api_key', trim($config));
}
if (!get('sitehost_api_key')) {
writeln('<error>SKIPPING SITEHOST BACKUP - sitehost_api_key not set - You may need to add a the sitehost-api-key.txt to your parent directory or update your docker image</error>');
return;
}
if (!get('sitehost_client_id')) {
writeln('<error>SKIPPING SITEHOST BACKUP - sitehost_client_id not set</error>');
return;
}
if (!get('sitehost_server_name')) {
writeln('<error>SKIPPING SITEHOST BACKUP - sitehost_server_name not set</error>');
return;
}
if (!get('sitehost_stack_name')) {
writeln('<error>SKIPPING SITEHOST BACKUP - sitehost_stack_name not set</error>');
return;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sitehost.nz/1.2/cloud/stack/backup.json");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$body = array(
'apikey' => get('sitehost_api_key'),
'client_id' => get('sitehost_client_id'),
'server' => get('sitehost_server_name'),
'name' => get('sitehost_stack_name'),
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
writeln('<info>Trigger a containter backup {{sitehost_stack_name}} on {{sitehost_server_name}}</info>');
$backupResponse = curl_exec($ch);
$backupStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
writeln('<info>Response from Sitehost: ' . $backupResponse . '</info>');
curl_close($ch);
$backupResponse = json_decode($backupResponse, true);
// if response.status is true, start looping the job endpoint to wait for a completed response
if ($backupStatusCode == 200 && isset($backupResponse['return']) && isset($backupResponse['return']['job_id'])) {
writeln('<info>Waiting for backup to complete...</info>');
$job_url = "https://api.sitehost.nz/1.2/job/get.json?apikey=" . get('sitehost_api_key') . "&job_id=" . $backupResponse['return']['job_id'] . "&type=scheduler"; // scheduler or daemon
$ch = curl_init();
// Loop until the job is completed
do {
sleep(5); //. Check every 5 seconds for completed backup
curl_setopt($ch, CURLOPT_URL, $job_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$jobResponse = curl_exec($ch);
$jobStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Decode the response and check the status
$jobStatus = json_decode($jobResponse, true);
} while ($jobStatus['return']['state'] != 'Completed');
curl_close($ch);
writeln('<info>Backup completed</info>');
}
});
task('savefromremote:assets', function () {
writeln('<info>Save assets from SiteHost</info>');
writeln('<comment>Running rsync command rsync -avhzrP {{remote_user}}@{{alias}}:{{shared_path}}/wp-content/uploads/ ./wp-content/uploads/</comment>');
//-a, –archive | -v, –verbose | -h, –human-readable | -z, –compress | r, –recursive | -P, --partial and --progress
runLocally('rsync -avhzrP {{remote_user}}@{{alias}}:{{shared_path}}/wp-content/uploads/ ./wp-content/uploads/', ['timeout' => 1800]);
writeln('<info>==============</info>');
writeln('<info>Done!</info>');
writeln('<info>==============</info>');
});
task('savefromremote:plugins', function () {
writeln('<info>Save plugins from SiteHost</info>');
writeln('<comment>Running rsync command rsync -avhzrP {{remote_user}}@{{alias}}:{{shared_path}}/wp-content/plugins/ ./wp-content/plugins/</comment>');
//-a, –archive | -v, –verbose | -h, –human-readable | -z, –compress | r, –recursive | -P, --partial and --progress
runLocally('rsync -avhzrP {{remote_user}}@{{alias}}:{{shared_path}}/wp-content/plugins/ ./wp-content/plugins/', ['timeout' => 1800]);
writeln('<info>==============</info>');
writeln('<info>Done!</info>');
writeln('<info>==============</info>');
});
task('savefromremote:db', function () {
writeln('<info>Retrieving db from SiteHost</info>');
writeln('<comment>Running rsync command "rsync -avhzrP {{remote_user}}@{{alias}}:{{remote_db_backup_path}} ./from-remote/"</comment>');
//-a, –archive | -v, –verbose | -h, –human-readable | -z, –compress | r, –recursive | -P, --partial and --progress
runLocally('rsync -aqzrP {{remote_user}}@{{alias}}:{{remote_db_backup_path}} ./from-remote/', ['timeout' => 1800]);
writeln('<info>Done!</info>');
});
/**
* Syncs the database and uploads from a remote environment (uat or prod) to the local machine.
*
* Prompts for the source environment, then:
* - Exports the remote database via wp-cli and imports it locally.
* - Runs a search-replace to swap the remote site URL for the local URL.
* - Rsyncs wp-content/uploads from the remote server to the local project.
* - Flushes rewrite rules locally.
*
* Requires `local_url` to be set in the host configuration.
*/
task('syncfromremote', function () {
$stages = array_values(array_unique(array_filter(
array_map(fn($host) => $host->get('labels')['stage'] ?? null, Deployer::get()->hosts->toArray())
)));
$stage = askChoice(
'Which environment do you want to sync FROM?',
$stages,
0
);
// Apply stage selection
on(select("stage={$stage}"), function ($host) {
if (!askConfirmation("This will OVERWRITE your LOCAL database and uploads from {$host->getHostname()}. Continue?")) {
writeln('Aborting sync.');
return;
}
writeln("<info>Syncing from {$host->getHostname()} ({$host->get('labels')['stage']})</info>");
writeln('<comment>Detecting remote URL...</comment>');
$remoteUrl = run("cd {{shared_path}} && wp option get siteurl --allow-root");
$localUrl = 'http://' . get('local_url');
writeln("<info>Remote URL: {$remoteUrl}</info>");
writeln("<info>Local URL: {$localUrl}</info>");
writeln('<comment>Syncing database...</comment>');
runLocally(
"ssh {{remote_user}}@{{hostname}} 'cd {{shared_path}} && wp db export - --allow-root' | wp db import -",
['timeout' => 1800]
);
writeln('<info>Database imported locally</info>');
writeln('<comment>Running search-replace...</comment>');
runLocally(
"wp search-replace '{$remoteUrl}' '{$localUrl}' --all-tables --precise --skip-columns=guid",
['timeout' => 1800]
);
writeln('<info>URLs updated</info>');
writeln('<comment>Syncing uploads...</comment>');
runLocally(
"rsync -avhzrP {{remote_user}}@{{hostname}}:{{shared_path}}/wp-content/uploads/ ./wp-content/uploads/",
['timeout' => 1800]
);
writeln('<info>Uploads synced</info>');
runLocally("wp rewrite flush");
writeln('<info>Permalinks flushed</info>');
writeln('<info>Sync complete</info>');
});
});
// ==================================================================
// Deployment
/**
* Prompts for confirmation before deploying to production.
* Aborts the deployment if the user does not confirm.
*/
task('confirm', function () {
if (!askConfirmation('Are you sure you want to deploy to production?')) {
writeln('Ok, quitting.');
throw new GracefulShutdownException('User aborted the deployment.');
}
})->select('stage=prod');
/**
* Uploads wp-config-env.php from the local project root to the remote server.
* Aborts deployment if the file is not present locally.
*/
task('deploy:config', function () {
// Find project root (3 levels up from this file)
$localFile = dirname(__DIR__, 3) . '/wp-config-env.php';
if (!file_exists($localFile)) {
throw new GracefulShutdownException('wp-config-env.php not found locally. Deployment aborted.');
}
$remoteUser = get('remote_user');
$alias = get('alias');
$remotePath = '/container/application/public/';
writeln("<comment>Running rsync command: rsync -avP $localFile $remoteUser@$alias:$remotePath</comment>");
runLocally("rsync -avP $localFile $remoteUser@$alias:$remotePath", ['timeout' => 60]);
writeln('<info>wp-config-env.php uploaded to /container/application/public/</info>');
});
/**
* Creates a symlink from the shared WordPress theme directory to the current
* Deployer release. Moves aside any existing non-symlinked theme directory.
*/
task('wordpress:theme:symlink', function () {
$wpThemeDir = '{{shared_path}}/{{sub_directory}}/{{theme_folder}}';
$deployerCurrent = '{{deploy_path}}/current';
run('mkdir -p ' . dirname($wpThemeDir));
if (test('[ ! -L ' . $wpThemeDir . ' ] && [ -d ' . $wpThemeDir . ' ]')) {
writeln('<comment>Theme directory exists as real dir — moving aside to {{theme_folder}}-backup</comment>');
run('mv ' . $wpThemeDir . ' ' . $wpThemeDir . '-backup');
}
run('ln -sfn ' . $deployerCurrent . ' ' . $wpThemeDir);
writeln('<info>Symlinked: ' . $wpThemeDir . ' → ' . $deployerCurrent . '</info>');
});
desc('Deploy theme');
task('deploy', [
'confirm',
'deploy:config',
'deploy:prepare',
'deploy:publish',
'wordpress:theme:symlink',
]);
after('deploy:failed', 'deploy:unlock');