-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.install.php
501 lines (462 loc) · 18.5 KB
/
script.install.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
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
/**
* @package CG Secure
* Version : 3.1.0
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
* @copyright (C) 2024 ConseilGouz. All Rights Reserved.
* @author ConseilGouz
* @license GNU/GPLv3
*/
// no direct access
defined('_JEXEC') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Installer\Installer;
use Joomla\CMS\Language\Text as JText;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Version;
use Joomla\Database\DatabaseInterface;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Folder;
use Joomla\CMS\Table\Table;
class PlgSystemCgsecureInstallerInstallerScript
{
private $min_joomla_version = '4.0.0';
private $min_php_version = '7.4';
private $name = 'CG Secure';
private $extname = '';
private $extension_type = '';
private $plugin_folder = '';
private $previous_version = '';
private $dir = null;
private $installerName = 'cgsecureinstaller';
private $cgsecure_force_update_version = "3.1.0";
private $security;
private $config;
public const SERVER_CONFIG_FILE_HTACCESS = '.htaccess';
public const SERVER_CONFIG_FILE_NONE = '';
public const CGPATH = '/media/com_cgsecure';
public function __construct()
{
$this->dir = __DIR__;
}
public function preflight($route, $installer)
{
// To prevent installer from running twice if installing multiple extensions
if (! file_exists($this->dir . '/' . $this->installerName . '.xml')) {
return true;
}
Factory::getApplication()->getLanguage()->load('plgcgsecureinstaller', $this->dir);
if (! $this->passMinimumJoomlaVersion()) {
$this->uninstallInstaller();
return false;
}
if (! $this->passMinimumPHPVersion()) {
$this->uninstallInstaller();
return false;
}
$this->previous_version = null;
if (file_exists(JPATH_ADMINISTRATOR . '/components/com_cgsecure/cgsecure.xml')) {
$xml = simplexml_load_file(JPATH_ADMINISTRATOR . '/components/com_cgsecure/cgsecure.xml');
$this->previous_version = $xml->version;
}
// To prevent XML not found error
$this->createExtensionRoot();
return true;
}
public function postflight($route, $installer)
{
if (! in_array($route, ['install', 'update'])) {
return true;
}
// To prevent installer from running twice if installing multiple extensions
if (! file_exists($this->dir . '/' . $this->installerName . '.xml')) {
return true;
}
// First install the Library
if (! $this->installLibrary()) {
// Uninstall this installer
$this->uninstallInstaller();
return false;
}
// Then install the rest of the packages
if (! $this->installPackages()) {
// Uninstall this installer
$this->uninstallInstaller();
return false;
}
$this->postInstall();
Factory::getApplication()->enqueueMessage(JText::_('PKG_CGSECURE_XML_DESCRIPTION'), 'notice');
// Uninstall this installer
$this->uninstallInstaller();
return true;
}
private function postInstall()
{
// remove obsolete update sites
$db = Factory::getContainer()->get(DatabaseInterface::class);
$query = $db->getQuery(true)
->delete('#__update_sites')
->where($db->quoteName('location') . ' like "%432473037d.url-de-test.ws/%"');
$db->setQuery($query);
$db->execute();
// CG Secure is now on Github
$query = $db->getQuery(true)
->delete('#__update_sites')
->where($db->quoteName('location') . ' like "%conseilgouz.com/updates/com_cgsecure%"');
$db->setQuery($query);
$db->execute();
// fix wrong type in update_sites
$query = $db->getQuery(true);
$query->update($db->quoteName('#__update_sites'))
->set($db->qn('type') . ' = "extension"')
->where($db->qn('type') . ' = "plugin"');
$db->setQuery($query);
try {
$db->execute();
} catch (RuntimeException $e) {
Log::add('unable to enable Plugin site_form_override', Log::ERROR, 'jerror');
}
// fix old cg secure system plugin in schemas table
$query = $db->getQuery(true)
->delete($db->quoteName('#__schemas'))
->where($db->quoteName('extension_id').' IN (select '.$db->qn("extension_id").' FROM '.$db->quoteName("#__extensions").'
WHERE '.$db->qn("type").' LIKE "plugin" AND '.$db->qn("folder").' LIKE "system" AND '.$db->qn("element").' LIKE "cgsecure")');
$db->setQuery($query);
$db->execute();
// remove obsolete file
$this->delete([
JPATH_ROOT.self::CGPATH . '/cg_no_robot/index.php',
]);
// replace index.php file in cg_no_robot dir by new version
$norobots = JPATH_ROOT.'/cg_no_robot';
if (is_dir($norobots)) { // cg_no_robot dir exists : copy new copy of index.php -------------------------------
$this->delete([$norobots.'/index.php']);
File::copy(
JPATH_ROOT.self::CGPATH . '/cg_no_robot/index.txt',
$norobots. '/index.php'
);
}
// Check if HTACCESS file has to be updated
$serverConfigFile = $this->getServerConfigFile('.htaccess');
if (!$serverConfigFile) { // no .htaccess file
return;
}
$readBuffer = file($serverConfigFile, FILE_IGNORE_NEW_LINES);
if (!$readBuffer) {// `file` couldn't read the htaccess we can't do anything at this point
return '';
}
$found = false;
$version = "";
foreach ($readBuffer as $id => $line) {
if (($pos = strpos($line, 'CG SECURE HTACCESS BEGIN')) !== false) { // line already exists in htaccess file
$version = trim(substr($line, $pos + 24, 10), '-');
$found = true;
break;
}
}
if (!$found) {
return;
} // No CG Secure line in htacces file => exit
if (!$version || ($version && ($version < $this->cgsecure_force_update_version))) {
$this->forceHTAccess(); // update htaccess
}
}
// Begin update HTACCESS -----------------------------------------------
private function forceHTAccess()
{
$serverConfigFile = $this->getServerConfigFile(self::SERVER_CONFIG_FILE_HTACCESS);
if (!$serverConfigFile) { // no .htaccess file : copy default htaccess.txt as .htaccess
$source = JPATH_ROOT.self::CGPATH .'/txt/htaccess.txt';
$dest = $this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS);
if (!copy($source, $dest)) {
return Factory::getApplication()->enqueueMessage(JText::_('CGSECURE : add HTACCESS error'));
}
}
// save htaccess file before adding CG Secure lines
$source = $this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS);
$dest = JPATH_ROOT.self::CGPATH .'/backup/htaccess.av'.gmdate('Ymd-His', time());
if (!copy($source, $dest)) {
return Factory::getApplication()->enqueueMessage(JText::_('CGSECURE : save HTACCESS error'));
}
$current = $this->read_current($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS));
$rejips = $this->get_current_ips($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS));
if (file_exists(JPATH_ROOT.self::CGPATH .'/txt/custom.txt')) { // custom file exists : use it
$cgFile = $this->read_cgfile(JPATH_ROOT.self::CGPATH .'/txt/custom.txt');
} else { // no custom file : use cgaccess.txt file
$cgFile = $this->read_cgfile(JPATH_ROOT.self::CGPATH .'/txt/cgaccess.txt');
}
$this->config = $this->getParams();
$specific = $this->config->specific;
if ($specific) {
$specific = '#------------------------CG SECURE SPECIFIC CODE BEGIN------------------------'.PHP_EOL.$specific.PHP_EOL;
$specific .= '#------------------------CG SECURE SPECIFIC CODE END------------------------'.PHP_EOL;
}
if ($this->merge_file($this->getServerConfigFilePath(self::SERVER_CONFIG_FILE_HTACCESS), $current, $cgFile, $rejips, $specific)) {
return; // everything OK => exit
}
Factory::getApplication()->enqueueMessage(JText::_('CGSECURE : Error during insert'));
return;
}
// from https://www.php.net/manual/en/function.lcg-value.php#75562
private function random_float($min, $max)
{
return ($min + lcg_value() * (abs($max - $min)));
}
private function getServerConfigFile($file)
{
if (file_exists($this->getServerConfigFilePath($file))
&& substr(strtolower($_SERVER['SERVER_SOFTWARE']), 0, 6) === 'apache') {
return $this->getServerConfigFilePath($file);
}
return '';
}
private function getServerConfigFilePath($file)
{
return JPATH_ROOT . DIRECTORY_SEPARATOR . $file;
}
// read current .htaccess file and remove CG lines
private function read_current($afile)
{
$readBuffer = file($afile, FILE_IGNORE_NEW_LINES);
$outBuffer = '';
if (!$readBuffer) {// `file` couldn't read the htaccess we can't do anything at this point
return '';
}
$cgLines = false;
foreach ($readBuffer as $id => $line) {
if (strpos($line, 'CG SECURE HTACCESS BEGIN') !== false) {
$cgLines = true;
continue;
}
if (strpos($line, 'CG SECURE HTACCESS END') !== false) {
$cgLines = false;
continue;
}
if ($line === '#------------------------CG SECURE IP LIST BEGIN---------------------') {
$cgLines = true;
continue;
}
if ($line === '#------------------------CG SECURE IP LIST END--------------------') {
$cgLines = false;
continue;
}
if ($line === '#------------------------CG SECURE BAD ROBOTS BEGIN---------------------') {
$cgLines = true;
continue;
}
if ($line === '#------------------------CG SECURE BAD ROBOTS END---------------------') {
$cgLines = false;
continue;
}
if ($line === '#------------------------CG SECURE SPECIFIC CODE BEGIN------------------------') {
$cgLines = true;
continue;
}
if ($line === '#------------------------CG SECURE SPECIFIC CODE END------------------------') {
$cgLines = false;
continue;
}
if ($cgLines) {
// When we are between our makers all content should be removed
continue;
}
$outBuffer .= $line . PHP_EOL;
}
return $outBuffer;
}
private function read_cgfile($afile)
{
$readBuffer = file($afile, FILE_IGNORE_NEW_LINES);
$this->config = $this->getParams();
$this->security = $this->config->security;
if ($this->config->multi == '1') {// site multi-adresse
$server = '('.str_replace(',', '|', $this->config->get('multisite', '')).')';
$dir = "";
} elseif ($this->config->subdir == '1') { // site in subdir ?
$server = $_SERVER['SERVER_NAME'];
$dir = "/".$this->config->subdirsite;
} else {
$server = $_SERVER['SERVER_NAME'];
$dir = "";
}
$sitename = str_replace('.', '\.', $server);
$sitename = str_replace('www\.', '', $sitename); // remove www
$outBuffer = '';
if (!$readBuffer) {// `file` couldn't read the htaccess we can't do anything at this point
return '';
}
foreach ($readBuffer as $id => $line) {
if (strpos($line, '??site??') !== false) {
$line = str_replace('??site??', $sitename, $line);
}
if (strpos($line, '??dir??') !== false) {
$line = str_replace('??dir??', $dir, $line);
}
if (strpos($line, '??security??') !== false) {
$line = str_replace('??security??', $this->security, $line);
}
$outBuffer .= $line . PHP_EOL;
}
return $outBuffer;
}
// get current ips from .htaccess file
private function get_current_ips($afile)
{
$readBuffer = file($afile, FILE_IGNORE_NEW_LINES);
$outBuffer = '';
if (!$readBuffer) {// `file` couldn't read the htaccess we can't do anything at this point
return '';
}
$cgLines = false;
foreach ($readBuffer as $id => $line) {
if (($line === '#------------------------CG SECURE IP LIST BEGIN---------------------') && ($outBuffer == '')) {
$cgLines = true;
}
if (($line === '#------------------------CG SECURE IP LIST END--------------------') && $cgLines) {
$cgLines = false;
$outBuffer .= $line . PHP_EOL;
}
if (!$cgLines) {
// remove everything outsite the markers
continue;
}
$outBuffer .= $line . PHP_EOL;
}
return $outBuffer;
}
private function getParams()
{
$db = Factory::getDBo();
$table = Table::getInstance('ConfigTable','ConseilGouz\\Component\\CGSecure\Administrator\\Table\\', array('dbo' => $db));
$params = json_decode($table->getSecureParams()->params);
return $params;
}
private function merge_file($file, $current, $cgFile, $rejips, $specific)
{
$pathToFile = $file;
if (file_exists($pathToFile)) {
if (is_readable($pathToFile)) {
$records = $rejips.$specific.$cgFile.$current; // pour éviter les conflits, on se met devant....
// Write the htaccess using the Frameworks File Class
return File::write($pathToFile, $records);
}
}
return Factory::getApplication()->enqueueMessage(JText::_('CGSECURE : merge error'));
}
// End HTACCESS update -------------------------------------------------------------
private function createExtensionRoot()
{
$destination = JPATH_PLUGINS . '/system/' . $this->installerName;
Folder::create($destination);
File::copy(
$this->dir . '/' . $this->installerName . '.xml',
$destination . '/' . $this->installerName . '.xml'
);
}
// Check if Joomla version passes minimum requirement
private function passMinimumJoomlaVersion()
{
$j = new Version();
$version = $j->getShortVersion();
if (version_compare($version, $this->min_joomla_version, '<')) {
Factory::getApplication()->enqueueMessage(
JText::sprintf(
'NOT_COMPATIBLE_UPDATE',
'<strong>' . JVERSION . '</strong>',
'<strong>' . $this->min_joomla_version . '</strong>'
),
'error'
);
return false;
}
return true;
}
// Check if PHP version passes minimum requirement
private function passMinimumPHPVersion()
{
if (version_compare(PHP_VERSION, $this->min_php_version, '<')) {
Factory::getApplication()->enqueueMessage(
JText::sprintf(
'NOT_COMPATIBLE_PHP',
'<strong>' . PHP_VERSION . '</strong>',
'<strong>' . $this->min_php_version . '</strong>'
),
'error'
);
return false;
}
return true;
}
private function installPackages()
{
$packages = Folder::folders($this->dir . '/packages');
$packages = array_diff($packages, ['library_cgsecure']);
foreach ($packages as $package) {
if (! $this->installPackage($package)) {
return false;
}
}
// enable plugins
$db = Factory::getContainer()->get(DatabaseInterface::class);
$conditions = array(
$db->qn('type') . ' = ' . $db->q('plugin'),
$db->qn('element') . ' = ' . $db->quote('cgsecure')
);
$fields = array($db->qn('enabled') . ' = 1');
$query = $db->getQuery(true);
$query->update($db->quoteName('#__extensions'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$db->execute();
} catch (RuntimeException $e) {
Log::add('unable to enable Plugins CGSecure', Log::ERROR, 'jerror');
}
return true;
}
private function installPackage($package)
{
$tmpInstaller = new Installer();
$installed = $tmpInstaller->install($this->dir . '/packages/' . $package);
return $installed;
}
private function installLibrary()
{
if (! $this->installPackage('library_cgsecure')
|| ! $this->installPackage('plg_system_cgsecure')) {
Factory::getApplication()->enqueueMessage(JText::_('ERROR_INSTALLATION_LIBRARY_FAILED'), 'error');
return false;
}
Factory::getCache()->clean('_system');
return true;
}
private function uninstallInstaller()
{
if (! is_dir(JPATH_PLUGINS . '/system/' . $this->installerName)) {
return;
}
$this->delete([
JPATH_PLUGINS . '/system/' . $this->installerName . '/language',
JPATH_PLUGINS . '/system/' . $this->installerName,
]);
$db = Factory::getDbo();
$query = $db->getQuery(true)
->delete('#__extensions')
->where($db->quoteName('element') . ' = ' . $db->quote($this->installerName))
->where($db->quoteName('folder') . ' = ' . $db->quote('system'))
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'));
$db->setQuery($query);
$db->execute();
Factory::getCache()->clean('_system');
}
public function delete($files = [])
{
foreach ($files as $file) {
if (is_dir($file)) {
Folder::delete($file);
}
if (is_file($file)) {
File::delete($file);
}
}
}
}