summaryrefslogtreecommitdiffstats
path: root/modules/migrate/application/clicommands/PreferencesCommand.php
blob: 11d1edb946cdba425e64b11cd89ba070f5b829fe (plain)
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
<?php
/* Icinga Web 2 | (c) 2021 Icinga GmbH | GPLv2+ */

namespace Icinga\Module\Migrate\Clicommands;

use Icinga\Application\Config;
use Icinga\Application\Logger;
use Icinga\Cli\Command;
use Icinga\Data\ConfigObject;
use Icinga\Data\ResourceFactory;
use Icinga\Exception\NotReadableError;
use Icinga\Exception\NotWritableError;
use Icinga\File\Ini\IniParser;
use Icinga\User;
use Icinga\User\Preferences\PreferencesStore;
use Icinga\Util\DirectoryIterator;

class PreferencesCommand extends Command
{
    /**
     * Migrate local INI user preferences to a database
     *
     * USAGE
     *
     *  icingacli migrate preferences [options]
     *
     * OPTIONS:
     *
     *  --resource=<resource-name>  The resource to use, if no current database config backend is configured.
     *  --no-set-config-backend     Do not set the given resource as config backend automatically
     */
    public function indexAction()
    {
        $resource = Config::app()->get('global', 'config_resource');
        if (empty($resource)) {
            $resource = $this->params->getRequired('resource');
        }

        $resourceConfig = ResourceFactory::getResourceConfig($resource);
        if ($resourceConfig->db === 'mysql') {
            $resourceConfig->charset = 'utf8mb4';
        }

        $connection = ResourceFactory::createResource($resourceConfig);

        $preferencesPath = Config::resolvePath('preferences');
        if (! file_exists($preferencesPath)) {
            Logger::info('There are no local user preferences to migrate');
            return;
        }

        $rc = 0;

        $preferenceDirs = new DirectoryIterator($preferencesPath);
        foreach ($preferenceDirs as $preferenceDir) {
            if (! is_dir($preferenceDir)) {
                continue;
            }

            $userName = basename($preferenceDir);

            Logger::info('Migrating INI preferences for user "%s" to database...', $userName);

            $dbStore = new PreferencesStore(new ConfigObject(['connection' => $connection]), new User($userName));

            try {
                $dbStore->load();
                $dbStore->save(
                    new User\Preferences(
                        $this->loadIniFile($preferencesPath, (new User($userName))->getUsername())
                    )
                );
            } catch (NotReadableError $e) {
                if ($e->getPrevious() !== null) {
                    Logger::error('%s: %s', $e->getMessage(), $e->getPrevious()->getMessage());
                } else {
                    Logger::error($e->getMessage());
                }

                $rc = 128;
            } catch (NotWritableError $e) {
                Logger::error('%s: %s', $e->getMessage(), $e->getPrevious()->getMessage());
                $rc = 256;
            }
        }

        if ($rc > 0) {
            Logger::error('Failed to migrate some user preferences');
            exit($rc);
        }

        if ($this->params->has('resource') && ! $this->params->has('no-set-config-backend')) {
            $appConfig = Config::app();
            $globalConfig = $appConfig->getSection('global');
            $globalConfig['config_resource'] = $resource;

            try {
                $appConfig->saveIni();
            } catch (NotWritableError $e) {
                Logger::error('Failed to update general configuration: %s', $e->getMessage());
                exit(256);
            }
        }

        Logger::info('Successfully migrated all local user preferences to database');
    }

    private function loadIniFile(string $filePath, string $username): array
    {
        $preferences = [];
        $preferencesFile = sprintf(
            '%s/%s/config.ini',
            $filePath,
            strtolower($username)
        );

        if (file_exists($preferencesFile)) {
            if (! is_readable($preferencesFile)) {
                throw new NotReadableError(
                    'Preferences INI file %s for user %s is not readable',
                    $preferencesFile,
                    $username
                );
            } else {
                $preferences = IniParser::parseIniFile($preferencesFile)->toArray();
            }
        }

        return $preferences;
    }
}