Internal: Migrate and improve settings from configuration.php to .env and hosting_limits.yml - refs #5702

pull/5756/head
christianbeeznst 1 year ago
parent c910deed85
commit 913d723d0a
  1. 7
      .env.dist
  2. 11
      config/hosting_limits.yml
  3. 1
      config/services.yaml
  4. 6
      public/main/admin/user_list.php
  5. 2
      public/main/admin/user_list_consent.php
  6. 13
      public/main/course_info/infocours.php
  7. 2
      public/main/cron/user_import/client.php
  8. 6
      public/main/inc/global.inc.php
  9. 68
      public/main/inc/lib/api.lib.php
  10. 8
      public/main/inc/lib/course.lib.php
  11. 12
      public/main/inc/lib/diagnoser.lib.php
  12. 10
      public/main/inc/lib/sessionmanager.lib.php
  13. 24
      public/main/inc/lib/usermanager.lib.php
  14. 63
      public/main/install/configuration.dist.php
  15. 13
      public/main/install/index.php
  16. 69
      public/main/install/install.lib.php
  17. 6
      public/main/survey/survey.lib.php
  18. 4
      public/plugin/advanced_subscription/src/AdvancedSubscriptionPlugin.php
  19. 7
      public/plugin/advanced_subscription/test/ws_session_user.php
  20. 123
      src/CoreBundle/Migrations/Schema/V200/Version20240806120000.php

@ -62,3 +62,10 @@ JWT_PASSPHRASE=your_secret_passphrase
# MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
###< symfony/messenger ###
###< additional settings ###
DB_MANAGER_ENABLED='{{DB_MANAGER_ENABLED}}'
SOFTWARE_NAME='{{SOFTWARE_NAME}}'
SOFTWARE_URL='{{SOFTWARE_URL}}'
DENY_DELETE_USERS='{{DENY_DELETE_USERS}}'
HOSTING_TOTAL_SIZE_LIMIT='{{HOSTING_TOTAL_SIZE_LIMIT}}'

@ -0,0 +1,11 @@
parameters:
hosting_limits:
urls:
1:
- hosting_limit_users: 100
- hosting_limit_teachers: 0
- hosting_limit_courses: 0
- hosting_limit_sessions: 0
- hosting_limit_disk_space: 500
- hosting_limit_active_courses: 0
- hosting_total_size_limit: 0

@ -117,3 +117,4 @@ cocur_slugify:
imports:
- {resource: ../src/CoreBundle/Resources/config/services.yml}
- {resource: ../src/LtiBundle/Resources/config/services.yml}
- {resource: ./hosting_limits.yml}

@ -718,7 +718,7 @@ function modify_filter($user_id, $url_params, $row): string
);
}
$deleteAllowed = !api_get_configuration_value('deny_delete_users');
$deleteAllowed = api_get_env_variable('DENY_DELETE_USERS', false);
if ($deleteAllowed) {
if ($user_id != $currentUserId &&
!$user_is_anonymous &&
@ -1297,14 +1297,14 @@ if ($showDeletedUsers) {
$table->set_column_filter(11, 'modify_deleted_filter');
$actionsList['restore'] = get_lang('Restore');
if (api_is_platform_admin() &&
!api_get_configuration_value('deny_delete_users')
!api_get_env_variable('DENY_DELETE_USERS', false)
) {
$actionsList['destroy'] = get_lang('Destroy');
}
} else {
$table->set_column_filter(11, 'modify_filter');
if (api_is_platform_admin() &&
!api_get_configuration_value('deny_delete_users')
!api_get_env_variable('DENY_DELETE_USERS', false)
) {
$actionsList['delete'] = get_lang('Remove from portal');
}

@ -613,7 +613,7 @@ $table->set_column_filter(10, 'requestTypeFilter');
// Only show empty actions bar if delete users has been blocked
$actionsList = [];
if (api_is_platform_admin() &&
!api_get_configuration_value('deny_delete_users')
!api_get_env_variable('DENY_DELETE_USERS', false)
) {
$actionsList['delete'] = get_lang('Remove from portal');
}

@ -949,15 +949,14 @@ if ($form->validate()) {
$illustrationRepo->deleteIllustration($courseEntity);
}
$limitCourses = api_get_configuration_value('hosting_limit_active_courses');
if ($limitCourses > 0) {
$access_url_id = api_get_current_access_url_id();
$limitCourses = get_hosting_limit($access_url_id, 'hosting_limit_active_courses');
if ($limitCourses !== null && $limitCourses > 0) {
$courseInfo = api_get_course_info_by_id($courseId);
// Check if
if (COURSE_VISIBILITY_HIDDEN == $courseInfo['visibility'] &&
$visibility != $courseInfo['visibility']
) {
$num = CourseManager::countActiveCourses($urlId);
if (COURSE_VISIBILITY_HIDDEN == $courseInfo['visibility'] && $visibility != $courseInfo['visibility']) {
$num = CourseManager::countActiveCourses($access_url_id);
if ($num >= $limitCourses) {
api_warn_hosting_contact('hosting_limit_active_courses');

@ -28,7 +28,7 @@ $response = $client->call(
'import_users',
[
'filepath' => api_get_path(SYS_UPLOAD_PATH)."users_import.csv",
'security_key' => api_get_configuration_value('security_key'),
'security_key' => api_get_env_variable('kernel.secret'),
]
);
echo $response;

@ -95,10 +95,8 @@ if ($isCli && $baseUrl) {
}
try {
// Load legacy configuration.php
if ($kernel->isInstalled()) {
require_once $kernel->getConfigurationFile();
} else {
if (!$kernel->isInstalled()) {
throw new Exception('Chamilo is not installed');
}

@ -24,6 +24,7 @@ use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Yaml\Yaml;
use ZipStream\Option\Archive;
use ZipStream\ZipStream;
use Chamilo\CoreBundle\Component\Utils\ActionIcon;
@ -4307,12 +4308,8 @@ function api_get_version()
*/
function api_get_software_name()
{
$name = api_get_configuration_value('software_name');
if (!empty($name)) {
$name = api_get_env_variable('SOFTWARE_NAME', 'Chamilo');
return $name;
} else {
return 'Chamilo';
}
}
function api_get_status_list()
@ -5213,7 +5210,7 @@ function api_is_valid_secret_key($original_key_secret, $security_key)
return false;
}
return (string) $original_key_secret === sha1($security_key);
return (string) $original_key_secret === hash('sha512', $security_key);
}
/**
@ -6816,6 +6813,65 @@ function api_get_configuration_value($variable)
return false;
}
/**
* Loads hosting limits from the YAML file.
*
* @return array The hosting limits.
*/
function load_hosting_limits(): array
{
$container = Container::$container;
$hostingLimits = $container->getParameter('hosting_limits');
return $hostingLimits['urls'] ?? [];
}
/**
* Gets a specific hosting limit.
*
* @param int $urlId The URL ID.
* @param string $limitName The name of the limit.
* @return mixed The value of the limit, or null if not found.
*/
function get_hosting_limit(int $urlId, string $limitName): mixed
{
$limits = load_hosting_limits();
foreach ($limits[$urlId] as $limitArray) {
if (isset($limitArray[$limitName])) {
return $limitArray[$limitName];
}
}
return null;
}
/**
* Retrieves an environment variable value with validation and handles boolean conversion.
*
* @param string $variable The name of the environment variable.
* @param mixed $default The default value to return if the variable is not set.
* @return mixed The value of the environment variable, converted to boolean if necessary, or the default value.
*/
function api_get_env_variable(string $variable, mixed $default = null): mixed
{
if (Container::$container->hasParameter($variable)) {
$value = Container::$container->getParameter($variable);
if ($value === '0') {
return false;
}
if ($value === '1') {
return true;
}
return $value;
}
return $default;
}
/**
* Retreives and returns a value in a hierarchical configuration array
* api_get_configuration_sub_value('a/b/c') returns api_get_configuration_value('a')['b']['c'].

@ -6709,9 +6709,11 @@ class CourseManager
*
* @return bool|string
*/
private static function checkCreateCourseAccessUrlParam($_configuration, $accessUrlId, $param, $msgLabel)
private static function checkCreateCourseAccessUrlParam($accessUrlId, $param, $msgLabel)
{
if (isset($_configuration[$accessUrlId][$param]) && $_configuration[$accessUrlId][$param] > 0) {
$hostingLimit = get_hosting_limit($accessUrlId, $param);
if ($hostingLimit !== null && $hostingLimit > 0) {
$num = null;
switch ($param) {
case 'hosting_limit_courses':
@ -6722,7 +6724,7 @@ class CourseManager
break;
}
if ($num && $num >= $_configuration[$accessUrlId][$param]) {
if ($num && $num >= $hostingLimit) {
api_warn_hosting_contact($param);
Display::addFlash(

@ -213,9 +213,8 @@ class Diagnoser
if (1 === $access_url_id) {
$size = '-';
global $_configuration;
$message2 = '';
if (1 === $access_url_id) {
if (api_is_windows_os()) {
$message2 .= get_lang('The space used on disk cannot be measured properly on Windows-based systems.');
} else {
@ -223,15 +222,14 @@ class Diagnoser
$du = exec('du -sh ' . $dir, $err);
list($size, $none) = explode("\t", $du);
unset($none);
$limit = get_hosting_limit($access_url_id, 'hosting_limit_disk_space');
if ($limit === null) {
$limit = 0;
if (isset($_configuration[$access_url_id])) {
if (isset($_configuration[$access_url_id]['hosting_limit_disk_space'])) {
$limit = $_configuration[$access_url_id]['hosting_limit_disk_space'];
}
}
$message2 .= sprintf(get_lang('Total space used by portal %s limit is %s MB'), $size, $limit);
}
}
$array[] = $this->build_setting(
self::STATUS_OK,

@ -167,13 +167,11 @@ class SessionManager
? (empty($accessUrlId) ? api_get_current_access_url_id() : (int) $accessUrlId)
: 1;
if (isset($_configuration[$accessUrlId]) &&
is_array($_configuration[$accessUrlId]) &&
isset($_configuration[$accessUrlId]['hosting_limit_sessions']) &&
$_configuration[$accessUrlId]['hosting_limit_sessions'] > 0
) {
$hostingLimitSessions = get_hosting_limit($accessUrlId, 'hosting_limit_sessions');
if ($hostingLimitSessions !== null && $hostingLimitSessions > 0) {
$num = self::count_sessions();
if ($num >= $_configuration[$accessUrlId]['hosting_limit_sessions']) {
if ($num >= $hostingLimitSessions) {
api_warn_hosting_contact('hosting_limit_sessions');
return get_lang('The number of sessions limit for this portal has been reached');

@ -183,12 +183,11 @@ class UserManager
}
}
if (isset($_configuration[$access_url_id]) &&
is_array($_configuration[$access_url_id]) &&
isset($_configuration[$access_url_id]['hosting_limit_users']) &&
$_configuration[$access_url_id]['hosting_limit_users'] > 0) {
$hostingLimitUsers = get_hosting_limit($access_url_id, 'hosting_limit_users');
if ($hostingLimitUsers !== null && $hostingLimitUsers > 0) {
$num = self::get_number_of_users();
if ($num >= $_configuration[$access_url_id]['hosting_limit_users']) {
if ($num >= $hostingLimitUsers) {
api_warn_hosting_contact('hosting_limit_users');
Display::addFlash(
Display::return_message(
@ -201,14 +200,12 @@ class UserManager
}
}
if (1 === $status &&
isset($_configuration[$access_url_id]) &&
is_array($_configuration[$access_url_id]) &&
isset($_configuration[$access_url_id]['hosting_limit_teachers']) &&
$_configuration[$access_url_id]['hosting_limit_teachers'] > 0
) {
if (1 === $status) {
$hostingLimitTeachers = get_hosting_limit($access_url_id, 'hosting_limit_teachers');
if ($hostingLimitTeachers !== null && $hostingLimitTeachers > 0) {
$num = self::get_number_of_users(1);
if ($num >= $_configuration[$access_url_id]['hosting_limit_teachers']) {
if ($num >= $hostingLimitTeachers) {
Display::addFlash(
Display::return_message(
get_lang('Sorry, this installation has a teachers limit, which has now been reached. To increase the number of teachers allowed on this Chamilo installation, please contact your hosting provider or, if available, upgrade to a superior hosting plan.'),
@ -220,6 +217,7 @@ class UserManager
return false;
}
}
}
if (empty($password)) {
if (PLATFORM_AUTH_SOURCE === $authSource) {
@ -612,7 +610,7 @@ class UserManager
*/
public static function canDeleteUser($user_id)
{
$deny = api_get_configuration_value('deny_delete_users');
$deny = api_get_env_variable('DENY_DELETE_USERS', false);
if ($deny) {
return false;

@ -1,63 +0,0 @@
<?php
// Chamilo version {NEW_VERSION}
// File generated by /install/index.php script - {DATE_GENERATED}
/* For licensing terms, see /license.txt */
/**
* This file contains a list of variables that can be modified by the campus site's server administrator.
* Pay attention when changing these variables, some changes may cause Chamilo to stop working.
* If you changed some settings and want to restore them, please have a look at
* configuration.dist.php. That file is an exact copy of the config file at install time.
* Besides the $_configuration, a $_settings array also exists, that
* contains variables that can be changed and will not break the platform.
* These optional settings are defined in the database, now
* (table settings_current).
*/
// Enable access to database management for platform admins.
$_configuration['db_manager_enabled'] = false;
/**
* Hosting settings - Allows you to set limits to the Chamilo portal when
* hosting it for a third party. These settings can be overwritten by an
* optionally-loaded extension file with only the settings (no comments).
* The settings use an index at the first level to represent the ID of the
* URL in case you use multi-url (otherwise it will always use 1, which is
* the ID of the only URL inside the access_url table).
*/
// Set a maximum number of users. Default (0) = no limit
$_configuration[1]['hosting_limit_users'] = 0;
// Set a maximum number of teachers. Default (0) = no limit
$_configuration[1]['hosting_limit_teachers'] = 0;
// Set a maximum number of courses. Default (0) = no limit
$_configuration[1]['hosting_limit_courses'] = 0;
// Set a maximum number of sessions. Default (0) = no limit
$_configuration[1]['hosting_limit_sessions'] = 0;
// Set a maximum disk space used, in MB (set to 1024 for 1GB, 5120 for 5GB, etc)
// Default (0) = no limit
$_configuration[1]['hosting_limit_disk_space'] = 0;
// Set a maximum number of usable courses. Default (0) = no limit.
// Should always be lower than the hosting_limit_courses.
// If set, defining a course as "hidden" will free room for
// new courses (up to the hosting_limit_courses, if any value is set there).
// hosting_limit_enabled_courses is the maximum number of courses that are *not* hidden.
$_configuration[1]['hosting_limit_active_courses'] = 0;
// Email to warn if limit was reached.
//$_configuration[1]['hosting_contact_mail'] = 'example@example.org';
// Portal size limit in MB (set to 1024 for 1GB, 5120 for 5GB, etc).
// Check main/cron/hosting_total_size_limit.php for how to use this limit.
$_configuration['hosting_total_size_limit'] = 0;
// Security word for password recovery
$_configuration['security_key'] = '{SECURITY_KEY}';
$_configuration['software_name'] = 'Chamilo';
$_configuration['software_url'] = 'https://chamilo.org/';
// Deny the elimination of users
$_configuration['deny_delete_users'] = false;
// KEEP THIS AT THE END
// -------- Custom DB changes
// Add user activation by confirmation email
// This option prevents the new user to login in the platform if your account is not confirmed via email
// You need add a new option called "confirmation" to the registration settings
//INSERT INTO settings_options (variable, value, display_text) VALUES ('allow_registration', 'confirmation', 'MailConfirmation');
// ------ (End) Custom DB changes

@ -174,7 +174,7 @@ if (!empty($_POST['updatePath'])) {
}
$checkMigrationStatus = [];
$isUpdateAvailable = isUpdateAvailable(api_get_path(SYS_PATH));
$isUpdateAvailable = isUpdateAvailable();
if (isset($_POST['step2_install']) || isset($_POST['step2_update_8']) || isset($_POST['step2_update_6'])) {
if (isset($_POST['step2_install'])) {
$installType = 'new';
@ -479,6 +479,11 @@ if (isset($_POST['step2'])) {
'{{APP_INSTALLED}}' => 1,
'{{APP_ENCRYPT_METHOD}}' => $encryptPassForm,
'{{APP_SECRET}}' => generateRandomToken(),
'{{DB_MANAGER_ENABLED}}' => '0',
'{{SOFTWARE_NAME}}' => 'Chamilo',
'{{SOFTWARE_URL}}' => $institutionUrlForm,
'{{DENY_DELETE_USERS}}' => '0',
'{{HOSTING_TOTAL_SIZE_LIMIT}}' => '0',
];
error_log('Update env file');
updateEnvFile($distFile, $envFile, $params);
@ -568,6 +573,11 @@ if (isset($_POST['step2'])) {
'{{APP_INSTALLED}}' => 1,
'{{APP_ENCRYPT_METHOD}}' => $encryptPassForm,
'{{APP_SECRET}}' => generateRandomToken(),
'{{DB_MANAGER_ENABLED}}' => '0',
'{{SOFTWARE_NAME}}' => 'Chamilo',
'{{SOFTWARE_URL}}' => $institutionUrlForm,
'{{DENY_DELETE_USERS}}' => '0',
'{{HOSTING_TOTAL_SIZE_LIMIT}}' => '0',
];
updateEnvFile($distFile, $envFile, $params);
@ -620,7 +630,6 @@ if (isset($_POST['step2'])) {
$allowSelfRegProf,
$installationProfile
);
writeSystemConfigFile(api_get_path(SYMFONY_SYS_PATH).'config/configuration.php');
error_log('Finish installation');
} else {
error_log('ERROR during installation.');

@ -245,45 +245,6 @@ function set_file_folder_permissions()
@chmod('..', 0755); //set permissions on parent dir of install dir
}
/**
* Write the main system config file.
*
* @param string $path Path to the config file
*/
function writeSystemConfigFile($path)
{
$content = file_get_contents(__DIR__.'/'.SYSTEM_CONFIG_FILENAME);
$config['{DATE_GENERATED}'] = date('r');
$config['{SECURITY_KEY}'] = md5(uniqid(rand().time()));
foreach ($config as $key => $value) {
$content = str_replace($key, $value, $content);
}
$fp = @fopen($path, 'w');
if (!$fp) {
echo '<strong>
<font color="red">Your script doesn\'t have write access to the config directory</font></strong><br />
<em>('.str_replace('\\', '/', realpath($path)).')</em><br /><br />
You probably do not have write access on Chamilo root directory,
i.e. you should <em>CHMOD 777</em> or <em>755</em> or <em>775</em>.<br /><br />
Your problems can be related on two possible causes:<br />
<ul>
<li>Permission problems.<br />Try initially with <em>chmod -R 777</em> and increase restrictions gradually.</li>
<li>PHP is running in <a href="http://www.php.net/manual/en/features.safe-mode.php" target="_blank">Safe-Mode</a>.
If possible, try to switch it off.</li>
</ul>
<a href="http://forum.chamilo.org/" target="_blank">Read about this problem in Support Forum</a><br /><br />
Please go back to step 5.
<p><input type="submit" name="step5" value="&lt; Back" /></p>
</td></tr></table></form></body></html>';
exit;
}
fwrite($fp, $content);
fclose($fp);
}
/**
* This function returns the value of a parameter from the configuration file.
*
@ -795,7 +756,7 @@ function display_requirements(
'pathPermissions' => $pathPermissions,
'step2_update_6' => isset($_POST['step2_update_6']),
'notWritable' => $notWritable,
'existsConfigurationFile' => file_exists(api_get_path(CONFIGURATION_PATH).'configuration.php'),
'existsConfigurationFile' => false,
'deprecatedToRemove' => $deprecatedToRemove,
'installError' => $error,
];
@ -1379,6 +1340,12 @@ function updateEnvFile($distFile, $envFile, $params)
'DATABASE_PASSWORD',
'APP_INSTALLED',
'APP_ENCRYPT_METHOD',
'APP_SECRET',
'DB_MANAGER_ENABLED',
'SOFTWARE_NAME',
'SOFTWARE_URL',
'DENY_DELETE_USERS',
'HOSTING_TOTAL_SIZE_LIMIT',
];
foreach ($requirements as $requirement) {
@ -1725,22 +1692,20 @@ function checkCanCreateFile(string $file): bool
/**
* Checks if the update option is available.
*
* Checks the existence of the "app" folder and the "configuration.php" file
* to determine if an update is available from version 1.11.x.
* This function checks the APP_INSTALLED environment variable to determine if the application is already installed.
* If the APP_INSTALLED variable is set to '1', it indicates that an update is available.
*
* @param string $baseDir The base directory.
* @return bool True if the update is available, false otherwise.
* @return bool True if the application is already installed (APP_INSTALLED='1'), otherwise false.
*/
function isUpdateAvailable(string $baseDir): bool
function isUpdateAvailable(): bool
{
// Path to the "app" folder
$appFolder = $baseDir.'/../app';
// Path to the "configuration.php" file
$configFile = $baseDir.'/../app/config/configuration.php';
// Check if APP_INSTALLED is set and equals '1'
if (isset($_ENV['APP_INSTALLED']) && $_ENV['APP_INSTALLED'] === '1') {
return true;
}
// Check the existence of the "app" folder and the "configuration.php" file
return is_dir($appFolder) && file_exists($configFile);
// If APP_INSTALLED is not found or not set to '1', assume the application is not installed
return false;
}
function checkMigrationStatus(): array

@ -1493,11 +1493,13 @@ class SurveyManager
*
* @return string
*/
public static function generate_survey_hash($survey_id, $course_id, $session_id, $group_id)
public static function generate_survey_hash(int $survey_id, int $course_id, int $session_id, int $group_id): string
{
$securityKey = api_get_env_variable('kernel.secret');
return hash(
'sha512',
api_get_configuration_value('security_key').'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id
$securityKey.'_'.$course_id.'_'.$session_id.'_'.$group_id.'_'.$survey_id
);
}

@ -1291,7 +1291,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
*/
public function generateHash($data)
{
$key = sha1($this->get('secret_key'));
$key = hash('sha512', $this->get('secret_key'));
// Prepare array to have specific type variables
$dataPrepared['action'] = (string) ($data['action']);
$dataPrepared['sessionId'] = (int) ($data['sessionId']);
@ -1301,7 +1301,7 @@ class AdvancedSubscriptionPlugin extends Plugin implements HookPluginInterface
$dataPrepared['newStatus'] = (int) ($data['newStatus']);
$dataPrepared = serialize($dataPrepared);
return sha1($dataPrepared.$key);
return hash('sha512', $dataPrepared.$key);
}
/**

@ -48,17 +48,16 @@ if (is_file(api_get_path(WEB_CODE_PATH).'webservices/webservice-auth-ip.conf.php
}
}
global $_configuration;
if ($check_ip) {
$security_key = $_configuration['security_key'];
$security_key = api_get_env_variable('kernel.secret');
} else {
$security_key = $ip.$_configuration['security_key'];
$security_key = $ip.api_get_env_variable('kernel.secret');;
//error_log($secret_key.'-'.$security_key);
}
/*
* End WSHelperVerifyKey.
*/
$params['secret_key'] = sha1($security_key);
$params['secret_key'] = hash('sha512', $security_key);
// Registration soap wsdl
$wsUrl = api_get_path(WEB_CODE_PATH).'webservices/registration.soap.php?wsdl';

@ -0,0 +1,123 @@
<?php
declare(strict_types=1);
/* For licensing terms, see /license.txt */
namespace Chamilo\CoreBundle\Migrations\Schema\V200;
use Chamilo\CoreBundle\Migrations\AbstractMigrationChamilo;
use Doctrine\DBAL\Schema\Schema;
final class Version20240806120000 extends AbstractMigrationChamilo
{
public function getDescription(): string
{
return 'Migrate settings from configuration.php to .env and hosting_limits.yml files';
}
public function up(Schema $schema): void
{
global $_configuration;
$rootPath = $this->getRootPath();
$oldConfigPath = $rootPath . '/app/config/configuration.php';
if (!\in_array($oldConfigPath, get_included_files(), true)) {
include_once $oldConfigPath;
}
// Update .env and .env.local files
$this->updateEnvFiles($rootPath, [
"DB_MANAGER_ENABLED" => $_configuration['db_manager_enabled'] ? '1' : '0',
"SOFTWARE_NAME" => $_configuration['software_name'],
"SOFTWARE_URL" => $_configuration['software_url'],
"DENY_DELETE_USERS" => $_configuration['deny_delete_users'] ? '1' : '0',
"HOSTING_TOTAL_SIZE_LIMIT" => $_configuration['hosting_total_size_limit'] ?? 0
]);
// Ensure the hosting_limits.yml file exists
$hostingLimitsFile = $rootPath . '/config/hosting_limits.yml';
$hostingLimits = ['hosting_limits' => ['urls' => []]];
// Prepare hosting limits
foreach ($_configuration as $key => $config) {
if (is_numeric($key) && is_array($config)) {
// Handle configurations specific to URL IDs
$hostingLimits['hosting_limits']['urls'][$key] = [
['hosting_limit_users' => $config['hosting_limit_users'] ?? 0],
['hosting_limit_teachers' => $config['hosting_limit_teachers'] ?? 0],
['hosting_limit_courses' => $config['hosting_limit_courses'] ?? 0],
['hosting_limit_sessions' => $config['hosting_limit_sessions'] ?? 0],
['hosting_limit_disk_space' => $config['hosting_limit_disk_space'] ?? 0],
['hosting_limit_active_courses' => $config['hosting_limit_active_courses'] ?? 0],
['hosting_total_size_limit' => $_configuration['hosting_total_size_limit'] ?? 0]
];
}
}
// Format hosting limits as YAML
$yamlContent = "parameters:\n hosting_limits:\n urls:\n";
foreach ($hostingLimits['hosting_limits']['urls'] as $urlId => $limits) {
$yamlContent .= " {$urlId}:\n";
foreach ($limits as $limit) {
foreach ($limit as $key => $value) {
$yamlContent .= " - {$key}: {$value}\n";
}
}
}
// Write hosting limits to hosting_limits.yml
file_put_contents($hostingLimitsFile, $yamlContent);
}
public function down(Schema $schema): void {}
private function getRootPath(): string
{
return $this->container->getParameter('kernel.project_dir');
}
private function updateEnvFiles(string $rootPath, array $envSettings): void
{
$envFiles = [$rootPath . '/.env', $rootPath . '/.env.local'];
foreach ($envFiles as $envFile) {
if (file_exists($envFile)) {
$lines = file($envFile, FILE_IGNORE_NEW_LINES);
$updatedLines = [];
$existingKeys = [];
foreach ($lines as $line) {
if (strpos($line, '=') !== false) {
[$key, $value] = explode('=', $line, 2);
$key = trim($key);
if (array_key_exists($key, $envSettings)) {
$value = $envSettings[$key];
unset($envSettings[$key]);
}
$updatedLines[] = "{$key}={$value}";
$existingKeys[] = $key;
} else {
$updatedLines[] = $line;
}
}
// Add remaining new settings
foreach ($envSettings as $key => $value) {
if (!in_array($key, $existingKeys)) {
$updatedLines[] = "{$key}={$value}";
}
}
file_put_contents($envFile, implode(PHP_EOL, $updatedLines) . PHP_EOL);
} else {
// If the file does not exist, create it with the settings
$newContent = [];
foreach ($envSettings as $key => $value) {
$newContent[] = "{$key}={$value}";
}
file_put_contents($envFile, implode(PHP_EOL, $newContent) . PHP_EOL);
}
}
}
}
Loading…
Cancel
Save