Passed
Push — develop ( 3c5942...636dd4 )
by Nikolay
04:57
created

DateTime   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 119
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 60
dl 0
loc 119
rs 10
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A phpTimeZoneConfigure() 0 13 2
A timezoneConfigure() 0 22 3
A setDate() 0 25 2
A __construct() 0 4 1
A ntpDaemonConfigure() 0 21 4
1
<?php
2
/**
3
 * Copyright (C) MIKO LLC - All Rights Reserved
4
 * Unauthorized copying of this file, via any medium is strictly prohibited
5
 * Proprietary and confidential
6
 * Written by Nikolay Beketov, 6 2020
7
 *
8
 */
9
10
namespace MikoPBX\Core\System;
11
12
13
use Phalcon\Di;
14
15
class DateTime
16
{
17
    private $di;
18
    private MikoPBXConfig $mikoPBXConfig;
19
20
    /**
21
     * DateTime constructor.
22
     */
23
    public function __construct()
24
    {
25
        $this->di            = Di::getDefault();
26
        $this->mikoPBXConfig = new MikoPBXConfig();
27
    }
28
29
    /**
30
     * Setup system time
31
     *
32
     * @param $date - 2015.12.31-01:01:20
0 ignored issues
show
Documentation Bug introduced by
The doc comment - at position 0 could not be parsed: Unknown type name '-' at position 0 in -.
Loading history...
33
     *
34
     * @return array
35
     */
36
    public static function setDate($date): array
37
    {
38
        $result = [
39
            'result' => 'ERROR',
40
        ];
41
        // Преобразование числа к дате. Если необходимо.
42
        $date = Util::numberToDate($date);
43
        // Валидация даты.
44
        $re_date = '/^\d{4}\.\d{2}\.\d{2}\-\d{2}\:\d{2}\:\d{2}$/';
45
        preg_match_all($re_date, $date, $matches, PREG_SET_ORDER, 0);
46
        if (count($matches) > 0) {
47
            $result['result'] = 'Success';
48
            $arr_data         = [];
49
            $datePath         = Util::which('date');
50
            Util::mwExec("{$datePath} -s '{$date}'", $arr_data);
51
            $result['data'] = implode($arr_data);
52
        } else {
53
            $result['result'] = 'Success';
54
            $result['data']   = 'Update timezone only.';
55
        }
56
57
        $sys = new self();
58
        $sys->timezoneConfigure();
59
60
        return $result;
61
    }
62
63
64
    /**
65
     * Populates /etc/TZ with an appropriate time zone
66
     */
67
    public function timezoneConfigure(): void
68
    {
69
        $timezone = $this->mikoPBXConfig->getTimeZone();
70
71
        // include('timezones.php'); TODO:: Удалить и сам файл?
72
        @unlink("/etc/TZ");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

72
        /** @scrutinizer ignore-unhandled */ @unlink("/etc/TZ");

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
73
        @unlink("/etc/localtime");
74
75
        if ($timezone) {
76
            $zone_file = "/usr/share/zoneinfo/{$timezone}";
77
            if ( ! file_exists($zone_file)) {
78
                return;
79
            }
80
            $cpPath = Util::which('cp');
81
            Util::mwExec("{$cpPath}  {$zone_file} /etc/localtime");
82
            file_put_contents('/etc/TZ', $timezone);
83
            putenv("TZ={$timezone}");
84
            Util::mwExec("export TZ;");
85
        }
86
87
        $this->ntpDaemonConfigure();
88
        self::phpTimeZoneConfigure();
89
    }
90
91
    /**
92
     * Setup ntp daemon
93
     */
94
    private function ntpDaemonConfigure(): void
95
    {
96
        $ntp_server = $this->mikoPBXConfig->getServerNTP();
97
        if ( ! empty($ntp_server)) {
98
            $ntp_conf = "server {$ntp_server}";
99
        } else {
100
            $ntp_conf = 'server 0.pool.ntp.org
101
server 1.pool.ntp.org
102
server 2.pool.ntp.org';
103
        }
104
        Util::fileWriteContent('/etc/ntp.conf', $ntp_conf);
105
106
        if (Util::isSystemctl()) {
107
            return;
108
        }
109
        Util::killByName("ntpd");
110
        usleep(500000);
111
        $manual_time = $this->mikoPBXConfig->getGeneralSettings('PBXManualTimeSettings');
112
        if ($manual_time !== '1') {
113
            $ntpdPath = Util::which('ntpd');
114
            Util::mwExec($ntpdPath);
115
        }
116
    }
117
118
    /**
119
     * Setup timezone for PHP
120
     */
121
    public static function phpTimeZoneConfigure(): void
122
    {
123
        $mikoPBXConfig = new MikoPBXConfig();
124
        $timezone      = $mikoPBXConfig->getTimeZone();
125
        date_default_timezone_set($timezone);
126
        if (file_exists('/etc/TZ')) {
127
            $catPath = Util::which('cat');
128
            Util::mwExec("export TZ='$({$catPath} /etc/TZ)'");
129
        }
130
        $etcPhpIniPath = '/etc/php.ini';
131
        $contents = file_get_contents($etcPhpIniPath);
132
        $contents = preg_replace("/date.timezone(.*)/", 'date.timezone="'.$timezone.'"', $contents);
133
        Util::fileWriteContent($etcPhpIniPath, $contents);
134
    }
135
136
}