Repository navigation
Expand file tree
/
Copy pathupdatescript.php
More file actions
479 lines (458 loc) · 15.4 KB
/
Copy pathupdatescript.php
File metadata and controls
479 lines (458 loc) · 15.4 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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
<?php
/*
* @package BFStop Plugin (bfstop) for Joomla!
* @author Bernhard Froehler
* @copyright (C) Bernhard Froehler
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Installer\InstallerAdapter;
use Joomla\CMS\Installer\InstallerScript;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Router\Route;
use Joomla\Database\DatabaseInterface;
class PlgsystembfstopInstallerScript extends InstallerScript
{
// InstallerScript::preflight() refuses to install on anything older (and
// to replace a newer version of the plugin with an older one)
protected $minimumJoomla = '5.0.0';
protected $minimumPhp = '8.1.0';
// the version this update replaces, null for an installation
private $previousVersion = null;
// the .htaccess file whose block section of an earlier version could not
// be replaced, see replaceLegacyHtaccessSection()
private $htaccessNotRewritten = null;
// the bit of the "enabledForOrigin" setting for the Web Services API
// (Bfstop::OriginApi - the class of the version being replaced may be the
// one loaded while this runs)
private const OriginApi = 4;
/**
* Whether this update replaces a version before 2.0.0, which kept its
* settings in the Plugin Manager and didn't know the API. Not for a test
* release of 2.0.0 (2.0.0-dev sorts before 2.0.0-alpha1, -beta1 and -rc1).
*/
private function updatesFromBefore200($type)
{
return $type === 'update' && $this->previousVersion !== null &&
version_compare($this->previousVersion, '2.0.0-dev', '<');
}
public function __construct(InstallerAdapter $adapter) {}
public function install(InstallerAdapter $adapter)
{
// plugins install disabled by default, but bfstop only does anything
// useful while running, and all its settings now live in the
// component - so there's nothing left to configure before enabling it.
$db = Factory::getContainer()->get(DatabaseInterface::class);
$query = $db->getQuery(true)
->update($db->quoteName('#__extensions'))
->set($db->quoteName('enabled') . ' = 1')
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('bfstop'));
$db->setQuery($query);
$db->execute();
}
public function uninstall(InstallerAdapter $adapter)
{
// the log file holds IP addresses and usernames; don't leave it behind
try
{
$logPath = Factory::getApplication()->get('log_path');
foreach (array('plg_system_bfstop.log.php', 'plg_system_bfstop.1.log.php') as $file)
{
if ($logPath && is_file($logPath.'/'.$file))
{
@unlink($logPath.'/'.$file);
}
}
}
catch (\Throwable $e)
{
// a leftover log must not make the uninstallation fail
}
// without the plugin, nothing would ever take an address out of the
// block section of the .htaccess file again: the web server would
// refuse them for good
try
{
$file = self::htaccessFile(self::storedParams());
if (!self::removeHtaccessSection($file))
{
Factory::getApplication()->getLanguage()->load('plg_system_bfstop', JPATH_ADMINISTRATOR);
Factory::getApplication()->enqueueMessage(
Text::sprintf('PLG_SYSTEM_BFSTOP_UNINSTALL_HTACCESS_NOT_REMOVED', htmlspecialchars($file, ENT_QUOTES, 'UTF-8')),
'error'
);
}
}
catch (\Throwable $e)
{
// neither may this
}
}
/**
* The plugin's settings as they are stored, null if they can't be read.
*/
private static function storedParams()
{
$db = Factory::getContainer()->get(DatabaseInterface::class);
$query = $db->getQuery(true)
->select($db->quoteName('params'))
->from($db->quoteName('#__extensions'))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('bfstop'));
$db->setQuery($query);
$params = json_decode((string) $db->loadResult(), true);
return is_array($params) ? $params : null;
}
/**
* The .htaccess file the plugin writes with the settings $params.
*/
private static function htaccessFile($params)
{
$htaccessPath = (is_array($params) && (string) ($params['htaccessPath'] ?? '') !== '')
? (string) $params['htaccessPath'] : JPATH_ROOT;
return rtrim($htaccessPath, '/\\').'/.htaccess';
}
public function preflight($type, $adapter)
{
if (!parent::preflight($type, $adapter))
{
return false;
}
if ($type === 'update')
{
$manifest = $this->getItemArray('manifest_cache', '#__extensions', 'name', 'plg_system_bfstop');
$this->previousVersion = isset($manifest['version']) ? (string) $manifest['version'] : null;
$this->renameWhitelistTable();
}
return true;
}
/**
* For version 1.4.2, the whitelist table was renamed to allowlist, but only
* for updates; new installations kept the old name. This has to happen
* before the update SQL, which runs after preflight() but before update()
* and changes the allowlist table (MySQL only - PostgreSQL is supported
* from 2.0.0 on, so no such table exists there).
*/
private function renameWhitelistTable()
{
$db = Factory::getContainer()->get(DatabaseInterface::class);
if ($db->getServerType() !== 'mysql')
{
return;
}
$prefix = $db->getPrefix();
$tables = array_map('strtolower', $db->getTableList());
if (in_array(strtolower($prefix.'bfstop_whitelist'), $tables, true) &&
!in_array(strtolower($prefix.'bfstop_allowlist'), $tables, true))
{
$db->setQuery('RENAME TABLE '.$db->quoteName('#__bfstop_whitelist').
' TO '.$db->quoteName('#__bfstop_allowlist'));
$db->execute();
}
}
public function postflight($type, $adapter)
{
if ($this->htaccessNotRewritten !== null)
{
Factory::getApplication()->getLanguage()->load('plg_system_bfstop', JPATH_ADMINISTRATOR);
Factory::getApplication()->enqueueMessage(
Text::sprintf('PLG_SYSTEM_BFSTOP_UPDATE_HTACCESS_NOT_REWRITTEN', htmlspecialchars($this->htaccessNotRewritten, ENT_QUOTES, 'UTF-8')),
'error'
);
}
// only for the update from a version before the settings moved, not
// for every later update
if ($this->updatesFromBefore200($type))
{
$lang = Factory::getApplication()->getLanguage();
$lang->load('plg_system_bfstop', JPATH_ADMINISTRATOR);
$settingsUrl = Route::_('index.php?option=com_bfstop&view=settings', false);
Factory::getApplication()->enqueueMessage(
Text::sprintf('PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_HINT', $settingsUrl),
'warning'
);
// update() switched the protection of the API on, see there
Factory::getApplication()->enqueueMessage(
Text::sprintf('PLG_SYSTEM_BFSTOP_UPDATE_2_0_0_API_HINT', $settingsUrl),
'warning'
);
}
}
public function update(InstallerAdapter $adapter)
{
$db = Factory::getContainer()->get(DatabaseInterface::class);
// for 2.0.0, the previously separate blockEnabled/useHtaccess switches
// and the (never released) two-value blockMode were unified into a
// single four-value blockMode setting (#187); every real install still
// has the old pre-2.0 config, so migrate it once into the equivalent
// unified value
try
{
$query = $db->getQuery(true)
->select($db->quoteName('params'))
->from($db->quoteName('#__extensions'))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('bfstop'));
$db->setQuery($query);
$params = json_decode((string) $db->loadResult(), true);
$changed = false;
if (is_array($params) && !array_key_exists('blockMode', $params))
{
$newMode = 'full';
if (array_key_exists('blockEnabled', $params) && (string) $params['blockEnabled'] === '0')
{
$newMode = 'off';
}
elseif (array_key_exists('useHtaccess', $params) && (string) $params['useHtaccess'] === '1')
{
$newMode = 'htaccess';
}
$params['blockMode'] = $newMode;
$changed = true;
}
// 2.0.0 also protects logins through the Web Services API, which
// the frontend/backend setting of earlier versions didn't cover:
// switched on for every site, as it is for a new installation (a
// setting that was never saved gets the new default anyway).
// postflight() tells the administrator
if (is_array($params) && $this->updatesFromBefore200('update') &&
array_key_exists('enabledForOrigin', $params))
{
$params['enabledForOrigin'] = ((int) $params['enabledForOrigin']) | self::OriginApi;
$changed = true;
}
// whatever the blocking mode is now: the file may still hold the
// section of the time .htaccess blocking was used
$htaccessFile = self::htaccessFile($params);
if (!self::replaceLegacyHtaccessSection($htaccessFile))
{
$this->htaccessNotRewritten = $htaccessFile;
}
if ($changed)
{
$query = $db->getQuery(true)
->update($db->quoteName('#__extensions'))
->set($db->quoteName('params') . ' = ' . $db->quote(json_encode($params)))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('element') . ' = ' . $db->quote('bfstop'));
$db->setQuery($query);
$db->execute();
}
}
catch (Exception $e)
{
// if the extension row can't be found/updated, there's nothing we can do
// Log::add("Update ERROR: ".$e->getMessage(), Log::ERROR, 'Update');
}
}
/**
* Whether $value is an IP address, or a network in CIDR notation - all
* that may get into a condition of the web server's configuration.
*/
private static function isAddressOrNetwork($value)
{
$parts = explode('/', (string) $value);
if (count($parts) > 2 || filter_var($parts[0], FILTER_VALIDATE_IP) === false)
{
return false;
}
return count($parts) === 1 || (preg_match('/^[0-9]{1,3}\z/', $parts[1]) === 1 &&
(int) $parts[1] <= (strpos($parts[0], ':') !== false ? 128 : 32));
}
/**
* Replaces the block section which versions up to 2.0.0 wrote into the
* .htaccess file - "<RequireAll> Require all granted, Require not ip ...
* </RequireAll>" - by the form the plugin writes now (see the plugin's
* HtaccessHelper), keeping the addresses, the 403 message and any lines
* added by hand. Apache combines the authorization directives at the top
* level of a configuration section with an implicit <RequireAny>, so the
* "Require all granted" let everybody who wasn't blocked past every other
* access control of the directory (HTTP authentication, "Require ip",
* "Require all denied").
*
* Done here, without the plugin's classes: those of the version being
* replaced may be the ones loaded in this request. What lets the links of
* unblock emails through needs the site's path, which an update from the
* command line doesn't know: the plugin's daily maintenance adds it (see
* HtaccessHelper::upgradeFormat()).
*
* @return bool false if the section is there and the file couldn't be written
*/
public static function replaceLegacyHtaccessSection($file)
{
if (!is_file($file))
{
return true;
}
$content = @file_get_contents($file);
if (!is_string($content))
{
return false;
}
$lines = explode("\n", $content);
list($begin, $end) = self::findSection($lines);
if ($begin === null)
{
return true;
}
$addresses = array();
$errorDocument = null;
$other = array();
$legacy = false;
for ($i = $begin + 1; $i < $end; ++$i)
{
$line = trim($lines[$i]);
if ($line === '')
{
continue;
}
if (in_array($line, array('<RequireAll>', 'Require all granted', '</RequireAll>'), true))
{
$legacy = true;
}
elseif (strpos($line, 'Require not ip ') === 0)
{
$legacy = true;
$address = substr($line, strlen('Require not ip '));
if (self::isAddressOrNetwork($address))
{
$addresses[] = $address;
}
}
elseif (strpos($line, 'ErrorDocument 403 ') === 0)
{
$errorDocument = $line;
}
else
{
$other[] = rtrim($lines[$i], "\r");
}
}
if (!$legacy)
{
return true;
}
$section = array();
// as many addresses per <If> as HtaccessHelper::AddressesPerCondition
foreach (array_chunk(array_values(array_unique($addresses)), 50) as $chunk)
{
$conditions = array();
foreach ($chunk as $address)
{
$conditions[] = "-R '".$address."'";
}
$section[] = '<If "'.implode(' || ', $conditions).'">';
$section[] = 'Require all denied';
$section[] = '</If>';
}
if ($errorDocument !== null)
{
$section[] = $errorDocument;
}
array_splice($lines, $begin + 1, $end - $begin - 1, array_merge($section, $other));
return self::writeFile($file, implode("\n", $lines));
}
/**
* The first and the last line of the block section of the .htaccess file
* with the lines $lines (its markers), or two nulls if it has none.
*
* @return array{0: int|null, 1: int|null}
*/
private static function findSection(array $lines)
{
$begin = null;
foreach ($lines as $i => $line)
{
if ($begin === null && strpos($line, '# BEGIN BFStop Blocks') !== false)
{
$begin = $i;
}
elseif ($begin !== null && strpos($line, '# END BFStop Blocks') !== false)
{
return array($begin, $i);
}
}
return array(null, null);
}
/**
* Replaces the content of $file as a whole, like the plugin's
* HtaccessHelper::write() does.
*/
private static function writeFile($file, $content)
{
$target = is_link($file) ? (realpath($file) ?: $file) : $file;
$temporary = $target.'.bfstop-'.bin2hex(random_bytes(6));
if (@file_put_contents($temporary, $content) === strlen($content))
{
@chmod($temporary, fileperms($target) & 0777);
if (@rename($temporary, $target))
{
return true;
}
}
@unlink($temporary);
return @file_put_contents($target, $content, LOCK_EX) !== false;
}
/**
* Takes what the plugin writes out of the block section of the .htaccess
* file $file - the conditions with the blocked addresses, the 403
* message, and the lines of the form of earlier versions - for the
* uninstallation. Lines somebody else wrote into the section stay; a
* section without any goes as a whole, with its markers. Done without
* the plugin's classes, like replaceLegacyHtaccessSection().
*
* @return bool false if the section is there and the file couldn't be written
*/
public static function removeHtaccessSection($file)
{
if (!is_file($file))
{
return true;
}
$content = @file_get_contents($file);
if (!is_string($content))
{
return false;
}
$lines = explode("\n", $content);
list($begin, $end) = self::findSection($lines);
if ($begin === null)
{
return true;
}
$other = array();
for ($i = $begin + 1; $i < $end; ++$i)
{
$line = trim($lines[$i]);
if ($line === '' || strpos($line, '<If ') === 0 || strpos($line, 'Require not ip ') === 0 ||
strpos($line, 'ErrorDocument 403 ') === 0 ||
in_array($line, array('Require all denied', '</If>', '<RequireAll>', 'Require all granted', '</RequireAll>'), true))
{
continue;
}
$other[] = rtrim($lines[$i], "\r");
}
if (count($other) > 0)
{
array_splice($lines, $begin + 1, $end - $begin - 1, $other);
}
else
{
// the plugin writes an empty line after a section it puts at the
// beginning of the file
$length = $end - $begin + 1;
if (isset($lines[$end + 1]) && trim($lines[$end + 1]) === '' && isset($lines[$end + 2]))
{
++$length;
}
array_splice($lines, $begin, $length);
}
return self::writeFile($file, implode("\n", $lines));
}
}