centreonAPI.class.php 41.4 KB
Newer Older
Toufik MECHOUET's avatar
Toufik MECHOUET committed
1
<?php
2

Toufik MECHOUET's avatar
Toufik MECHOUET committed
3
/**
4
 * Copyright 2005-2021 CENTREON
Toufik MECHOUET's avatar
Toufik MECHOUET committed
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
 * Centreon is developped by : Julien Mathis and Romain Le Merlus under
 * GPL Licence 2.0.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation ; either version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, see <http://www.gnu.org/licenses>.
 *
 * Linking this program statically or dynamically with other modules is making a
 * combined work based on this program. Thus, the terms and conditions of the GNU
 * General Public License cover the whole combination.
 *
 * As a special exception, the copyright holders of this program give CENTREON
 * permission to link this program with independent modules to produce an executable,
 * regardless of the license terms of these independent modules, and to copy and
 * distribute the resulting executable under terms of CENTREON choice, provided that
 * CENTREON also meet, for each linked independent module, the terms  and conditions
 * of the license of that module. An independent module is a module which is not
 * derived from this program. If you modify this program, you may extend this
 * exception to your version of the program, but you are not obliged to do so. If you
 * do not wish to do so, delete this exception statement from your version.
 *
 * For more information : contact@centreon.com
 *
 */
36

37
namespace CentreonClapi;
Toufik MECHOUET's avatar
Toufik MECHOUET committed
38

39
40
41
use Security\Domain\Authentication\Exceptions\ProviderException;
use Security\Domain\Authentication\Model\LocalProvider;

42
require_once _CENTREON_PATH_ . "www/class/centreon-clapi/centreonExported.class.php";
Loic Laurent's avatar
Loic Laurent committed
43
44
require_once realpath(dirname(__FILE__) . "/../centreonDB.class.php");
require_once realpath(dirname(__FILE__) . "/../centreonXML.class.php");
45
46
require_once _CENTREON_PATH_ . "www/include/configuration/configGenerate/DB-Func.php";
require_once _CENTREON_PATH_ . 'www/class/config-generate/generate.class.php';
47
require_once __DIR__ . '/../centreonAuth.class.php';
48
49
require_once _CENTREON_PATH_ . "www/class/centreonAuth.LDAP.class.php";
require_once _CENTREON_PATH_ . 'www/class/centreonLog.class.php';
50
require_once realpath(dirname(__FILE__) . "/../centreonSession.class.php");
Toufik MECHOUET's avatar
Toufik MECHOUET committed
51
52
53


/**
54
 * General Centreon Management
Toufik MECHOUET's avatar
Toufik MECHOUET committed
55
56
57
58
59
60
61
 */
require_once "centreon.Config.Poller.class.php";

/**
 * Declare Centreon API
 *
 */
62
63
class CentreonAPI
{
Guillaume28's avatar
Guillaume28 committed
64
    private static $instance = null;
Toufik MECHOUET's avatar
Toufik MECHOUET committed
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    public $dateStart;
    public $login;
    public $password;
    public $action;
    public $object;
    public $options;
    public $args;
    public $DB;
    public $DBC;
    public $DBN;
    public $format;
    public $xmlObj;
    public $debug;
    public $variables;
    public $centreon_path;
    private $return_code;
Loic Laurent's avatar
Loic Laurent committed
82
    private $dependencyInjector;
Toufik MECHOUET's avatar
Toufik MECHOUET committed
83
84
    private $relationObject;
    private $objectTable;
85
    private $aExport = [];
86

87
88
89
90
91
    /**
     * @var string
     */
    public $delim = ';';

Loic Laurent's avatar
Loic Laurent committed
92
93
94
95
96
97
98
99
    public function __construct(
        $user,
        $password,
        $action,
        $centreon_path,
        $options,
        \Pimple\Container $dependencyInjector
    ) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
100
101
102
103
104
        /**
         * Set variables
         */
        $this->debug = 0;
        $this->return_code = 0;
Loic Laurent's avatar
Loic Laurent committed
105
        $this->dependencyInjector = $dependencyInjector;
Toufik MECHOUET's avatar
Toufik MECHOUET committed
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
        if (isset($user)) {
            $this->login = htmlentities($user, ENT_QUOTES);
        }
        if (isset($password)) {
            $this->password = htmlentities($password, ENT_QUOTES);
        }
        if (isset($action)) {
            $this->action = htmlentities(strtoupper($action), ENT_QUOTES);
        }

        $this->options = $options;
        $this->centreon_path = $centreon_path;

        if (isset($options["v"])) {
            $this->variables = $options["v"];
        } else {
            $this->variables = "";
        }

        if (isset($options["o"])) {
            $this->object = htmlentities(strtoupper($options["o"]), ENT_QUOTES);
        } else {
            $this->object = "";
        }

131
        $this->objectTable = [];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
132
133
134
135

        /**
         * Centreon DB Connexion
         */
Loic Laurent's avatar
Loic Laurent committed
136
137
        $this->DB = $this->dependencyInjector["configuration_db"];
        $this->DBC = $this->dependencyInjector["realtime_db"];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
138
139
        $this->dateStart = time();

140
141
        $this->relationObject = [];
        $this->relationObject["CMD"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
142
143
144
            'module' => 'core',
            'class' => 'Command',
            'export' => true
145
146
        ];
        $this->relationObject["HOST"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
147
148
            'module' => 'core',
            'class' => 'Host',
149
            'libs' => [
150
151
152
153
                'centreonService.class.php',
                'centreonHostGroup.class.php',
                'centreonContact.class.php',
                'centreonContactGroup.class.php'
154
            ],
Toufik MECHOUET's avatar
Toufik MECHOUET committed
155
            'export' => true
156
157
        ];
        $this->relationObject["SERVICE"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
158
159
            'module' => 'core',
            'class' => 'Service',
160
            'libs' => [
161
                'centreonHost.class.php'
162
            ],
Toufik MECHOUET's avatar
Toufik MECHOUET committed
163
            'export' => true
164
165
        ];
        $this->relationObject["HGSERVICE"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
166
167
168
            'module' => 'core',
            'class' => 'HostGroupService',
            'export' => true
169
170
        ];
        $this->relationObject["VENDOR"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
171
172
173
            'module' => 'core',
            'class' => 'Manufacturer',
            'export' => true
174
175
        ];
        $this->relationObject["TRAP"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
176
177
178
            'module' => 'core',
            'class' => 'Trap',
            'export' => true
179
180
        ];
        $this->relationObject["HG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
181
182
183
            'module' => 'core',
            'class' => 'HostGroup',
            'export' => true
184
185
        ];
        $this->relationObject["HC"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
186
187
188
            'module' => 'core',
            'class' => 'HostCategory',
            'export' => true
189
190
        ];
        $this->relationObject["SG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
191
192
193
            'module' => 'core',
            'class' => 'ServiceGroup',
            'export' => true
194
195
        ];
        $this->relationObject["SC"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
196
197
198
            'module' => 'core',
            'class' => 'ServiceCategory',
            'export' => true
199
200
        ];
        $this->relationObject["CONTACT"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
201
202
            'module' => 'core',
            'class' => 'Contact',
203
            'libs' => [
204
                'centreonCommand.class.php'
205
            ],
Toufik MECHOUET's avatar
Toufik MECHOUET committed
206
            'export' => true
207
208
209
210
211
212
213
        ];
        $this->relationObject["LDAPCONTACT"] = [
            'module' => 'core',
            'class' => 'LDAPContactRelation',
            'export' => true
        ];
        $this->relationObject["LDAP"] = [
214
215
216
            'module' => 'core',
            'class' => 'LDAP',
            'export' => true
217
218
        ];
        $this->relationObject["CONTACTTPL"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
219
220
221
            'module' => 'core',
            'class' => 'ContactTemplate',
            'export' => true
222
223
        ];
        $this->relationObject["CG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
224
225
226
            'module' => 'core',
            'class' => 'ContactGroup',
            'export' => true
227
        ];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
228
        /* Dependencies */
229
        $this->relationObject["DEP"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
230
231
232
            'module' => 'core',
            'class' => 'Dependency',
            'export' => true
233
        ];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
234
        /* Downtimes */
235
        $this->relationObject["DOWNTIME"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
236
237
238
            'module' => 'core',
            'class' => 'Downtime',
            'export' => true
239
        ];
240

loiclau's avatar
loiclau committed
241
        /* RtDowntimes */
242
        $this->relationObject["RTDOWNTIME"] = [
loiclau's avatar
loiclau committed
243
244
            'module' => 'core',
            'class' => 'RtDowntime',
245
            'export' => false
246
        ];
247

248
        /* RtAcknowledgement */
249
        $this->relationObject["RTACKNOWLEDGEMENT"] = [
250
251
252
            'module' => 'core',
            'class' => 'RtAcknowledgement',
            'export' => false
253
        ];
254

Toufik MECHOUET's avatar
Toufik MECHOUET committed
255
        /* Templates */
256
        $this->relationObject["HTPL"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
257
258
259
            'module' => 'core',
            'class' => 'HostTemplate',
            'export' => true
260
261
        ];
        $this->relationObject["STPL"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
262
263
264
            'module' => 'core',
            'class' => 'ServiceTemplate',
            'export' => true
265
266
        ];
        $this->relationObject["TP"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
267
268
269
            'module' => 'core',
            'class' => 'TimePeriod',
            'export' => true
270
271
        ];
        $this->relationObject["INSTANCE"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
272
273
274
            'module' => 'core',
            'class' => 'Instance',
            'export' => true
275
276
        ];
        $this->relationObject["ENGINECFG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
277
            'module' => 'core',
278
            'class' => 'EngineCfg',
Toufik MECHOUET's avatar
Toufik MECHOUET committed
279
            'export' => true
280
281
        ];
        $this->relationObject["CENTBROKERCFG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
282
283
284
            'module' => 'core',
            'class' => 'CentbrokerCfg',
            'export' => true
285
286
        ];
        $this->relationObject["RESOURCECFG"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
287
288
289
            'module' => 'core',
            'class' => 'ResourceCfg',
            'export' => true
290
291
        ];
        $this->relationObject["ACL"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
292
293
294
            'module' => 'core',
            'class' => 'ACL',
            'export' => false
295
296
        ];
        $this->relationObject["ACLGROUP"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
297
298
            'module' => 'core',
            'class' => 'ACLGroup',
299
            'export' => true
300
301
        ];
        $this->relationObject["ACLACTION"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
302
303
            'module' => 'core',
            'class' => 'ACLAction',
304
            'export' => true
305
306
        ];
        $this->relationObject["ACLMENU"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
307
308
            'module' => 'core',
            'class' => 'ACLMenu',
309
            'export' => true
310
311
        ];
        $this->relationObject["ACLRESOURCE"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
312
313
            'module' => 'core',
            'class' => 'ACLResource',
314
            'export' => true
315
316
        ];
        $this->relationObject["SETTINGS"] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
317
318
319
            'module' => 'core',
            'class' => 'Settings',
            'export' => false
320
        ];
321

Toufik MECHOUET's avatar
Toufik MECHOUET committed
322
        /* Get objects from modules */
323
        $objectsPath = [];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
324
        $DBRESULT = $this->DB->query("SELECT name FROM modules_informations");
Loic Laurent's avatar
Loic Laurent committed
325

326
        while ($row = $DBRESULT->fetch()) {
327
328
            $objectsPath = array_merge(
                $objectsPath,
Loic Laurent's avatar
Loic Laurent committed
329
                glob(_CENTREON_PATH_ . 'www/modules/' . $row['name'] . '/centreon-clapi/class/*.php')
330
            );
Toufik MECHOUET's avatar
Toufik MECHOUET committed
331
332
333
        }

        foreach ($objectsPath as $objectPath) {
334
            if (preg_match('/([\w-]+)\/centreon-clapi\/class\/centreon(\w+).class.php/', $objectPath, $matches)) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
335
                if (isset($matches[1]) && isset($matches[2])) {
336
                    $finalNamespace = substr($matches[1], 0, stripos($matches[1], '-server'));
337

338
339
340
                    $finalNamespace = implode(
                        '',
                        array_map(
Loic Laurent's avatar
Loic Laurent committed
341
342
                            function ($n) {
                                return ucfirst($n);
343
344
345
346
                            },
                            explode('-', $finalNamespace)
                        )
                    );
347
                    $this->relationObject[strtoupper($matches[2])] = [
Toufik MECHOUET's avatar
Toufik MECHOUET committed
348
                        'module' => $matches[1],
349
                        'namespace' => $finalNamespace,
Toufik MECHOUET's avatar
Toufik MECHOUET committed
350
351
                        'class' => $matches[2],
                        'export' => true
352
                    ];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
353
354
355
356
357
                }
            }
        }
    }

358
359
360
361
362
    /**
     *
     * @param void
     * @return CentreonApi
     */
Loic Laurent's avatar
Loic Laurent committed
363
364
365
366
367
368
369
370
    public static function getInstance(
        $user = null,
        $password = null,
        $action = null,
        $centreon_path = null,
        $options = null,
        $dependencyInjector = null
    ) {
Guillaume28's avatar
Guillaume28 committed
371
        if (is_null(self::$instance)) {
loiclau's avatar
loiclau committed
372
373
374
375
            if (is_null($dependencyInjector)) {
                $dependencyInjector = loadDependencyInjector();
            }

Guillaume28's avatar
Guillaume28 committed
376
            self::$instance = new CentreonAPI(
Loic Laurent's avatar
Loic Laurent committed
377
378
379
380
381
382
383
                $user,
                $password,
                $action,
                $centreon_path,
                $options,
                $dependencyInjector
            );
384
385
        }

Guillaume28's avatar
Guillaume28 committed
386
        return self::$instance;
387
388
    }

loiclau's avatar
loiclau committed
389
390
391
392
393
394
395
396
    /**
     * @return \Pimple\Container
     */
    public function getDependencyInjector()
    {
        return $this->dependencyInjector;
    }

Toufik MECHOUET's avatar
Toufik MECHOUET committed
397
398
399
400
401
402
    /**
     * Set Return Code
     *
     * @param int $returnCode
     * @return void
     */
403
404
    public function setReturnCode($returnCode)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
405
406
407
408
409
410
        $this->return_code = $returnCode;
    }

    /**
     * Centreon Object Management
     */
411
412
    protected function requireLibs($object)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
413
        if ($object != "") {
414
415
            if (
                isset($this->relationObject[$object]['class'])
416
                && isset($this->relationObject[$object]['module'])
Kevin Duret's avatar
Kevin Duret committed
417
                && !class_exists("\CentreonClapi\Centreon" . $this->relationObject[$object]['class'])
Loic Laurent's avatar
Loic Laurent committed
418
            ) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
419
420
421
                if ($this->relationObject[$object]['module'] == 'core') {
                    require_once "centreon" . $this->relationObject[$object]['class'] . ".class.php";
                } else {
Loic Laurent's avatar
Loic Laurent committed
422
                    require_once _CENTREON_PATH_ . "/www/modules/"
423
424
425
426
                        . $this->relationObject[$object]['module']
                        . "/centreon-clapi/class/centreon"
                        . $this->relationObject[$object]['class']
                        . ".class.php";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
427
428
429
                }
            }

430
431
            if (
                isset($this->relationObject[$object]['libs'])
Loic Laurent's avatar
Loic Laurent committed
432
433
                && !array_walk($this->relationObject[$object]['libs'], 'class_exists')
            ) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
434
435
436
437
                array_walk($this->relationObject[$object]['libs'], 'require_once');
            }
        } else {
            foreach ($this->relationObject as $sSynonyme => $oObjet) {
438
439
                if (
                    isset($oObjet['class'])
440
                    && isset($oObjet['module'])
loiclau's avatar
loiclau committed
441
                    && !class_exists("\CentreonClapi\Centreon" . $oObjet['class'])
Loic Laurent's avatar
Loic Laurent committed
442
                ) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
443
                    if ($oObjet['module'] == 'core') {
444
445
446
                        require_once _CENTREON_PATH_
                            . "www/class/centreon-clapi/centreon"
                            . $oObjet['class'] . ".class.php";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
447
                    } else {
448
449
450
451
                        require_once _CENTREON_PATH_
                            . "/www/modules/" . $oObjet['module']
                            . "/centreon-clapi/class/centreon"
                            . $oObjet['class'] . ".class.php";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
452
453
454
455
456
457
458
459
460
461
462
                    }
                }
                if (isset($oObjet['libs']) && !array_walk($oObjet['libs'], 'class_exists')) {
                    array_walk($oObjet['libs'], 'require_once');
                }
            }
        }

        /**
         * Default class needed
         */
Loic Laurent's avatar
Loic Laurent committed
463
464
        require_once _CLAPI_CLASS_ . "/centreonTimePeriod.class.php";
        require_once _CLAPI_CLASS_ . "/centreonACLResources.class.php";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
465
466
467
468
469
470
471
    }

    /**
     *
     * Set user login
     * @param varchar $login
     */
472
473
    public function setLogin($login)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
474
475
476
477
478
479
480
481
        $this->login = $login;
    }

    /**
     *
     * Set password of the user
     * @param varchar $password
     */
482
483
    public function setPassword($password)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
484
485
486
487
488
489
490
        $this->password = trim($password);
    }

    /**
     * Check user access and password
     *
     * @param boolean $useSha1
victorvassilev's avatar
victorvassilev committed
491
     * @param boolean $isWorker
Toufik MECHOUET's avatar
Toufik MECHOUET committed
492
493
     * @return return bool 1 if user can login
     */
victorvassilev's avatar
victorvassilev committed
494
    public function checkUser($useSha1 = false, $isWorker = false)
495
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
496
497
498
499
500
501
502
503
504
505
506
507
508
        if (!isset($this->login) || $this->login == "") {
            print "ERROR: Can not connect to centreon without login.\n";
            $this->printHelp();
            exit();
        }
        if (!isset($this->password) || $this->password == "") {
            print "ERROR: Can not connect to centreon without password.";
            $this->printHelp();
        }

        /**
         * Check Login / Password
         */
509
        $DBRESULT = $this->DB->prepare(
510
511
            "SELECT `contact`.*, `contact_password`.`password` AS `contact_passwd`,
            `contact_password`.`creation_date` AS `password_creation` FROM `contact`
512
513
            LEFT JOIN `contact_password` ON `contact_password`.`contact_id` = `contact`.`contact_id`
            WHERE `contact_alias` = :contactAlias
514
            AND `contact_activate` = '1' AND `contact_register` = '1'
515
516
517
518
            ORDER BY contact_password.creation_date DESC LIMIT 1"
        );
        $DBRESULT->bindParam(':contactAlias', $this->login, \PDO::PARAM_STR);
        $DBRESULT->execute();
loiclau's avatar
loiclau committed
519
        if ($DBRESULT->rowCount()) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
520
            $row = $DBRESULT->fetchRow();
victorvassilev's avatar
victorvassilev committed
521

522
523
524
525
            if ($row['contact_admin'] == 0) {
                print "You don't have permissions for CLAPI.\n";
                exit(1);
            }
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
            $contact = new \CentreonContact($this->DB);
            // Get Security Policy
            $securityPolicy = $contact->getPasswordSecurityPolicy();

            // Remove any blocking if it's not in the policy
            if ($securityPolicy['blocking_duration'] === null) {
                $this->removeBlockingTimeOnUser();
                $row['login_attempts'] = null;
                $row['blocking_time'] = null;
            }

            // Check if user is blocked
            if ($row['blocking_time'] !== null) {
                // If he is block and blocking duration is expired, unblock him
                if ((int) $row['blocking_time'] + (int) $securityPolicy['blocking_duration'] < time()) {
                    $this->removeBlockingTimeOnUser();
                    $row['login_attempts'] = null;
                    $row['blocking_time'] = null;
                } else {
                    $now = new \DateTime();
                    $expirationDate = (new \DateTime())->setTimestamp(
                        $row['blocking_time'] + $securityPolicy['blocking_duration']
                    );
                    $interval = (date_diff($now, $expirationDate))->format('%Dd %Hh %Im %Ss');
                    print "Unable to login, max login attempts has been reached. $interval left\n";
                    exit(1);
                }
            }

555
            $passwordExpirationDelay = $securityPolicy['password_expiration']['expiration_delay'];
556
            if (
557
558
                $passwordExpirationDelay !== null
                && (int) $row['password_creation'] + (int) $passwordExpirationDelay < time()
559
560
561
562
            ) {
                print "Unable to login, your password has expired.\n";
                exit(1);
            }
563

564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
            // Update password from md5 to bcrypt if old md5 password is valid.
            if (
                (str_starts_with($row["contact_passwd"], 'md5__')
                && $row["contact_passwd"] === $this->dependencyInjector['utils']->encodePass($this->password, 'md5'))
                || 'md5__' . $row["contact_passwd"] === $this->dependencyInjector['utils']->encodePass(
                    $this->password,
                    'md5'
                )
            ) {
                $hashedPassword = password_hash($this->password, \CentreonAuth::PASSWORD_HASH_ALGORITHM);
                $contact->replacePasswordByContactId(
                    (int) $row['contact_id'],
                    $row["contact_passwd"],
                    $hashedPassword
                );
                \CentreonClapi\CentreonUtils::setUserId($row['contact_id']);
580
                $this->removeBlockingTimeOnUser();
581
                return 1;
582
            }
583
            if (password_verify($this->password, $row['contact_passwd'])) {
584
                \CentreonClapi\CentreonUtils::setUserId($row['contact_id']);
585
                $this->removeBlockingTimeOnUser();
586
587
588
589
590
591
592
593
594
595
596
597
                return 1;
            } elseif ($row['contact_auth_type'] == 'ldap') {
                $CentreonLog = new \CentreonUserLog(-1, $this->DB);
                $centreonAuth = new \CentreonAuthLDAP(
                    $this->DB,
                    $CentreonLog,
                    $this->login,
                    $this->password,
                    $row,
                    $row['ar_id']
                );
                if ($centreonAuth->checkPassword() == 1) {
loiclau's avatar
loiclau committed
598
                    \CentreonClapi\CentreonUtils::setUserId($row['contact_id']);
599
600
                    return 1;
                }
Toufik MECHOUET's avatar
Toufik MECHOUET committed
601
            }
602
603
604
605
606
607
608
            if ($securityPolicy['attempts'] !== null && $securityPolicy['blocking_duration'] !== null) {
                $this->exitOnInvalidCredentials(
                    (int) $row['login_attempts'],
                    (int) $securityPolicy['attempts'],
                    (int) $securityPolicy['blocking_duration']
                );
            }
Toufik MECHOUET's avatar
Toufik MECHOUET committed
609
        }
610
611
        print "Invalid credentials.\n";
        exit(1);
Toufik MECHOUET's avatar
Toufik MECHOUET committed
612
613
614
615
616
617
    }

    /**
     *
     * return (print) a "\n"
     */
618
619
    public function endOfLine()
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
620
621
622
623
624
625
626
        print "\n";
    }

    /**
     *
     * close the current action
     */
627
628
    public function close()
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
629
630
631
632
633
634
635
636
637
638
        print "\n";
        exit($this->return_code);
    }

    /**
     * Print usage for using CLAPI ...
     *
     * @param boolean $dbOk | whether db is ok
     * @param int $returnCode
     */
639
640
    public function printHelp($dbOk = true, $returnCode = 0)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
641
642
643
644
645
646
        if ($dbOk) {
            $this->printLegals();
        }
        print "This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n";
        print "and you are welcome to modify and redistribute it under the GPL license\n\n";
        print "usage: ./centreon -u <LOGIN> -p <PASSWORD> [-s] -o <OBJECT> -a <ACTION> [-v]\n";
647
648
649
650
651
652
        print "  -s     Use SHA1 on password (default is MD5)\n";
        print "  -v     variables \n";
        print "  -h     Print help \n";
        print "  -V     Print version \n";
        print "  -o     Object type \n";
        print "  -a     Launch action on Centreon\n";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
653
654
655
656
657
        print "     Actions are the followings :\n";
        print "       - POLLERGENERATE: Build nagios configuration for a poller (poller id in -v parameters)\n";
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERGENERATE -v 1 \n";
        print "       - POLLERTEST: Test nagios configuration for a poller (poller id in -v parameters)\n";
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERTEST -v 1 \n";
Guillaume28's avatar
Guillaume28 committed
658
659
        print "       - CFGMOVE: move nagios configuration for a poller to final directory\n";
        print "         (poller id in -v parameters)\n";
Toufik MECHOUET's avatar
Toufik MECHOUET committed
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a CFGMOVE -v 1 \n";
        print "       - POLLERRESTART: Restart a poller (poller id in -v parameters)\n";
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERRESTART -v 1 \n";
        print "       - POLLERRELOAD: Reload a poller (poller id in -v parameters)\n";
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERRELOAD -v 1 \n";
        print "       - POLLERLIST: list all pollers\n";
        print "           #> ./centreon -u <LOGIN> -p <PASSWORD> -a POLLERLIST\n";
        print "\n";
        print "   For more information about configuration objects, please refer to CLAPI wiki:\n";
        print "      - http://documentation.centreon.com/docs/centreon-clapi/ \n";
        print "\n";
        print "Notes:\n";
        print "  - Actions can be written in lowercase chars\n";
        print "  - LOGIN and PASSWORD is an admin account of Centreon\n";
        print "\n";
        exit($returnCode);
    }

    /**
     *
     * Get variable passed in parameters
     * @param varchar $str
     */
683
684
    public function getVar($str)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
685
686
687
688
689
690
691
692
693
        $res = explode("=", $str);
        return $res[1];
    }

    /**
     *
     * Check that parameters are not empty
     * @param varchar $str
     */
694
695
    private function checkParameters($str)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
696
697
698
699
700
701
702
703
704
705
706
        if (!isset($this->options["v"]) || $this->options["v"] == "") {
            print "No options defined.\n";
            $this->return_code = 1;
            return 1;
        }
    }

    /**
     *
     * Init XML Flow
     */
707
708
    public function initXML()
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
709
710
711
712
713
        $this->xmlObj = new CentreonXML();
    }

    /**
     * Main function : Launch action
714
715
     *
     * @param boolean $exit If exit or return the return code
Toufik MECHOUET's avatar
Toufik MECHOUET committed
716
     */
717
718
    public function launchAction($exit = true)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
719
        $action = strtoupper($this->action);
720

Toufik MECHOUET's avatar
Toufik MECHOUET committed
721
722
723
724
725
726
727
728
729
730
731
        /**
         * Debug
         */
        if ($this->debug) {
            print "DEBUG : $action\n";
        }

        /**
         * Check method availability before using it.
         */
        if ($this->object) {
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
            $isService = $this->dependencyInjector['centreon.clapi']->has($this->object);

            if ($isService === true) {
                $objName = $this->dependencyInjector['centreon.clapi']->get($this->object);
            } else {
                /**
                 * Require needed class
                 */
                $this->requireLibs($this->object);

                /**
                 * Check class declaration
                 */
                if (isset($this->relationObject[$this->object]['class'])) {
                    if ($this->relationObject[$this->object]['module'] === 'core') {
                        $objName = "\CentreonClapi\centreon" . $this->relationObject[$this->object]['class'];
                    } else {
                        $objName = $this->relationObject[$this->object]['namespace'] . "\CentreonClapi\Centreon" .
                            $this->relationObject[$this->object]['class'];
                    }
752
                } else {
753
                    $objName = "";
754
                }
755

756
757
758
759
                if (!isset($this->relationObject[$this->object]['class']) || !class_exists($objName)) {
                    print "Object $this->object not found in Centreon API.\n";
                    return 1;
                }
Toufik MECHOUET's avatar
Toufik MECHOUET committed
760
            }
761

762
            $obj = new $objName($this->dependencyInjector);
763

Toufik MECHOUET's avatar
Toufik MECHOUET committed
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
            if (method_exists($obj, $action) || method_exists($obj, "__call")) {
                $this->return_code = $obj->$action($this->variables);
            } else {
                print "Method not implemented into Centreon API.\n";
                return 1;
            }
        } else {
            if (method_exists($this, $action)) {
                $this->return_code = $this->$action();
                print "Return code end : " . $this->return_code . "\n";
            } else {
                print "Method not implemented into Centreon API.\n";
                $this->return_code = 1;
            }
        }
779

780
        if ($exit) {
781
            exit($this->return_code);
782
783
784
        } else {
            return $this->return_code;
        }
Toufik MECHOUET's avatar
Toufik MECHOUET committed
785
786
787
788
789
    }

    /**
     * Import Scenario file
     */
790
791
    public function import($filename)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
792
793
794
795
796
797
798
799
800
801
802
803
804
        $globalReturn = 0;

        $this->fileExists($filename);

        /*
         * Open File in order to read it.
         */
        $handle = fopen($filename, 'r');
        if ($handle) {
            $i = 0;
            while ($string = fgets($handle)) {
                $i++;
                $tab = preg_split('/;/', $string);
805
                if (strlen(trim($string)) != 0 && !preg_match('/^\{OBJECT_TYPE\}/', $string)) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
806
807
808
809
810
811
812
813
814
815
816
817
                    $this->object = trim($tab[0]);
                    $this->action = trim($tab[1]);
                    $this->variables = trim(substr($string, strlen($tab[0] . ";" . $tab[1] . ";")));
                    if ($this->debug == 1) {
                        print "Object : " . $this->object . "\n";
                        print "Action : " . $this->action . "\n";
                        print "VARIABLES : " . $this->variables . "\n\n";
                    }
                    try {
                        $this->launchActionForImport();
                    } catch (CentreonClapiException $e) {
                        echo "Line $i : " . $e->getMessage() . "\n";
818
                    } catch (\Exception $e) {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
819
820
821
822
823
824
825
826
827
828
829
830
                        echo "Line $i : " . $e->getMessage() . "\n";
                    }
                    if ($this->return_code) {
                        $globalReturn = 1;
                    }
                }
            }
            fclose($handle);
        }
        return $globalReturn;
    }

831
832
    public function launchActionForImport()
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
833
834
835
836
837
838
839
840
841
842
843
844
        $action = strtoupper($this->action);
        /**
         * Debug
         */
        if ($this->debug) {
            print "DEBUG : $action\n";
        }

        /**
         * Check method availability before using it.
         */
        if ($this->object) {
845
            $this->iniObject($this->object);
Toufik MECHOUET's avatar
Toufik MECHOUET committed
846
847
848
849

            /**
             * Check class declaration
             */
850
            $obj = $this->objectTable[$this->object];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
            if (method_exists($obj, $action) || method_exists($obj, "__call")) {
                $this->return_code = $obj->$action($this->variables);
            } else {
                print "Method not implemented into Centreon API.\n";
                return 1;
            }
        } else {
            if (method_exists($this, $action) || method_exists($this, "__call")) {
                $this->return_code = $this->$action();
            } else {
                print "Method not implemented into Centreon API.\n";
                $this->return_code = 1;
            }
        }
    }

867
868
869
    /**
     * @param $newOption
     */
870
    public function setOption($newOption): void
871
872
873
874
    {
        $this->options = $newOption;
    }

875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
    /**
     * @param $newVariables
     */
    public function setVariables($newVariables): void
    {
        $this->variables = $newVariables;
    }

    /**
     * @param $newPath
     */
    public function setCentreonPath($newPath): void
    {
        $this->centreon_path = $newPath;
    }

Toufik MECHOUET's avatar
Toufik MECHOUET committed
891
892
    /**
     * Export All configuration
893
     *
894
     * @param $withoutClose disable using of PHP exit function (default: false)
Toufik MECHOUET's avatar
Toufik MECHOUET committed
895
     */
896
    public function export($withoutClose = false)
897
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
898
899
900
        $this->requireLibs("");

        $this->sortClassExport();
901

Toufik MECHOUET's avatar
Toufik MECHOUET committed
902
        $this->initAllObjects();
903

904

905
        if (isset($this->options['select'])) {
906
907
            CentreonExported::getInstance()->setFilter(1);
            CentreonExported::getInstance()->setOptions($this->options);
908
            $selected = $this->options['select'];
909

910
911
912
            if (!is_array($this->options['select'])) {
                $selected = array($this->options['select']);
            }
913

914
915
            foreach ($selected as $select) {
                $splits = explode(';', $select);
916
917
918
919

                $splits[0] = isset($splits[0]) ? $splits[0] : null;
                $splits[1] = isset($splits[1]) ? $splits[1] : null;

920
921
922
                if (!isset($this->objectTable[$splits[0]])) {
                    print "Unknown object : $splits[0]\n";
                    $this->setReturnCode(1);
923
924
925
926
927
928

                    if ($withoutClose === false) {
                        $this->close();
                    } else {
                        return;
                    }
929
930
931
932
933
                } elseif (!is_null($splits[1])) {
                    $name = $splits[1];
                    if (isset($splits[2])) {
                        $name .= ';' . $splits[2];
                    }
934
                    if ($this->objectTable[$splits[0]]->getObjectId($name, CentreonObject::MULTIPLE_VALUE) == 0) {
935
936
                        echo "Unknown object : $splits[0];$splits[1]\n";
                        $this->setReturnCode(1);
937
938
939
940
941
                        if ($withoutClose === false) {
                            $this->close();
                        } else {
                            return;
                        }
942
943
944
                    } else {
                        $this->objectTable[$splits[0]]->export($name);
                    }
loiclau's avatar
loiclau committed
945
                } else {
946
                    $this->objectTable[$splits[0]]->export();
loiclau's avatar
loiclau committed
947
                }
Loic Laurent's avatar
Loic Laurent committed
948
            }
949
            return $this->return_code;
950
951
        } else {
            // header
952
            echo "{OBJECT_TYPE}{$this->delim}{COMMAND}{$this->delim}{PARAMETERS}\n";
953
954
955
956
957
            if (count($this->aExport) > 0) {
                foreach ($this->aExport as $oObjet) {
                    if (method_exists($this->objectTable[$oObjet], 'export')) {
                        $this->objectTable[$oObjet]->export();
                    }
Toufik MECHOUET's avatar
Toufik MECHOUET committed
958
959
960
961
962
963
964
965
966
967
968
                }
            }
        }
    }

    /**
     *
     * Init an object
     * @param unknown_type $DB
     * @param unknown_type $objname
     */
969
970
    private function iniObject($objname)
    {
971
        $className = '';
972
973
        if (
            isset($this->relationObject[$objname]['namespace'])
Loic Laurent's avatar
Loic Laurent committed
974
975
            && $this->relationObject[$objname]['namespace']
        ) {
976
977
978
            $className .= '\\' . $this->relationObject[$objname]['namespace'];
        }
        $className .= '\CentreonClapi\centreon' . $this->relationObject[$objname]['class'];
Toufik MECHOUET's avatar
Toufik MECHOUET committed
979
        $this->requireLibs($objname);
980
        $this->objectTable[$objname] = new $className($this->dependencyInjector, $objname);
Toufik MECHOUET's avatar
Toufik MECHOUET committed
981
982
983
984
985
    }

    /**
     * Init All object instance in order to export all informations
     */
986
987
    private function initAllObjects()
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
988
989
990
991
992
993
994
995
996
997
        if (count($this->aExport) > 0) {
            foreach ($this->aExport as $oObjet) {
                $this->iniObject($oObjet);
            }
        }
    }

    /**
     * Check if file exists
     */
998
999
    private function fileExists($filename)
    {
Toufik MECHOUET's avatar
Toufik MECHOUET committed
1000
        if (!file_exists($filename)) {
For faster browsing, not all history is shown. View entire blame