Completed
Pull Request — master (#404)
by Richard
11:08
created

UpgradeControl::determineLanguage()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 8
nop 0
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
class UpgradeControl
4
{
5
    /** @var PatchStatus[] */
6
    public $upgradeQueue = array();
7
8
    /** @var string[] */
9
    public $needWriteFiles = array();
10
11
    /** @var bool  */
12
    public $needUpgrade = false;
13
14
    /**
15
     * @var array support sites pulled from language files -- support.php
16
     */
17
    public $supportSites = array();
18
19
    /** @var bool */
20
    public $needMainfileRewrite = false;
21
22
    /** @var string[]  */
23
    public $mainfileKeys = array();
24
25
    /**
26
     * @var string language being used in the upgrade process
27
     */
28
    public $upgradeLanguage;
29
30
    /**
31
     * get a list of directories inside a directory
32
     *
33
     * @param string $dirname directory to search
34
     *
35
     * @return string[]
36
     */
37
    public function getDirList($dirname)
38
    {
39
        $dirlist = array();
40
        if (is_dir($dirname) && $handle = opendir($dirname)) {
41
            while (false !== ($file = readdir($handle))) {
42
                if (substr($file, 0, 1) !== '.' && strtolower($file) !== 'cvs') {
43
                    if (is_dir("{$dirname}/{$file}")) {
44
                        $dirlist[] = $file;
45
                    }
46
                }
47
            }
48
            closedir($handle);
49
            asort($dirlist);
50
            reset($dirlist);
51
        }
52
53
        return $dirlist;
54
    }
55
56
    /**
57
     * @return string[]
58
     */
59
    public function availableLanguages()
60
    {
61
        $languages = $this->getDirList('./language/');
62
        return $languages;
63
    }
64
65
66
    public function loadLanguage($domain, $language = null)
67
    {
68
        $supports = null;
69
70
        $language = (null === $language) ? $this->upgradeLanguage : $language;
71
72
        if (file_exists("./language/{$language}/{$domain}.php")) {
73
            include_once "./language/{$language}/{$domain}.php";
74
        } elseif (file_exists("./language/english/{$domain}.php")) {
75
            include_once "./language/english/{$domain}.php";
76
        }
77
78
        if (null !== $supports) {
79
            $this->supportSites = array_merge($this->supportSites, $supports);
80
        }
81
    }
82
83
    /**
84
     * Determine the language to use.
85
     *  - Xoops configuration
86
     *  - stored cookie
87
     *  - lang parameter passed to script
88
     * Save the result in a cookie
89
     *
90
     * @return string the language to use in the upgrade process
91
     */
92
    public function determineLanguage()
93
    {
94
        global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
95
96
        $upgrade_language = null;
97
        if (isset($xoopsConfig['language'])) {
98
            $upgrade_language = $xoopsConfig['language'];
99
        }
100
        $upgrade_language = !empty($_COOKIE['xo_upgrade_lang']) ? $_COOKIE['xo_upgrade_lang'] : $upgrade_language;
101
        $upgrade_language = Xmf\Request::getString('lang', $upgrade_language);
102
        $upgrade_language = (null === $xoopsConfig['language']) ? 'english' : $upgrade_language;
103
        setcookie('xo_upgrade_lang', $upgrade_language, null, null, null);
104
105
        $this->upgradeLanguage = $upgrade_language;
106
        $this->loadLanguage('upgrade');
107
108
        return $this->upgradeLanguage;
109
    }
110
111
    /**
112
     * Examine upgrade directories and determine:
113
     *  - which tasks need to run
114
     *  - which files need to be writable
115
     *
116
     * @return bool true of upgrade is needed
117
     */
118
    public function buildUpgradeQueue()
119
    {
120
        $dirs = $this->getDirList('.');
121
122
        /** @var PatchStatus[] $results */
123
        $results     = array();
124
        $files       = array();
125
        $this->needUpgrade = false;
126
127
        foreach ($dirs as $dir) {
128
            if (strpos($dir, '-to-')) {
129
                $upgrader = include_once "{$dir}/index.php";
130
                if (is_object($upgrader)) {
131
                    $results[$dir] = $upgrader->isApplied();
132
                    if (!($results[$dir]->applied)) {
133
                        $this->needUpgrade = true;
134
                        if (!empty($results[$dir]->files)) {
135
                            $files = array_merge($files, $upgrader->usedFiles);
136
                        }
137
                    }
138
                }
139
            }
140
        }
141
142
        if ($this->needUpgrade && !empty($files)) {
143
            foreach ($files as $k => $file) {
144
                $testFile = preg_match('/^([.\/\\\\:])|([a-z]:)/i', $file) ? $file : "../{$file}";
145
                if (is_writable($testFile) || !file_exists($testFile)) {
146
                    unset($files[$k]);
147
                }
148
            }
149
        }
150
151
        $this->upgradeQueue = $results;
0 ignored issues
show
Documentation Bug introduced by
It seems like $results of type array is incompatible with the declared type array<integer,object<PatchStatus>> of property $upgradeQueue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
152
        $this->needWriteFiles = $files;
153
154
        return $this->needUpgrade;
155
    }
156
157
    /**
158
     * Get count of patch sets that need to be applied.
159
     *
160
     * @return int count of patch sets to apply
161
     */
162
    public function countUpgradeQueue()
163
    {
164
        if (empty($this->upgradeQueue)) {
165
            $this->buildUpgradeQueue();
166
        }
167
        $count = 0;
168
        foreach ($this->upgradeQueue as $patch) {
169
            $count += ($patch->applied) ? 0 : 1;
170
        }
171
        return $count;
172
    }
173
174
    /**
175
     * @return string next unapplied patch directory
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
176
     */
177
    public function getNextPatch()
178
    {
179
        if (empty($this->upgradeQueue)) {
180
            $this->buildUpgradeQueue();
181
        }
182
        $next = false;
183
184
        foreach ($this->upgradeQueue as $directory => $patch) {
185
            if (!$patch->applied) {
186
                $next =  $directory;
187
                break;
188
            }
189
        }
190
        return $next;
191
    }
192
193
    /**
194
     * Return form consisting of a single button.
195
     *
196
     * @param string     $action     URL for form action
197
     * @param array|null $parameters array of parameters
198
     *
199
     * @return string
200
     */
201
    public function oneButtonContinueForm($action = 'index.php', $parameters = array('action' =>'next'))
202
    {
203
        $form  = '<form action="' . $action . '" method="post">';
204
        $form .= '<button class="btn btn-lg btn-success" type="submit">' . _CONTINUE;
205
        $form .= '  <span class="fa fa-caret-right"></span></button>';
206
        foreach ($parameters as $name => $value) {
0 ignored issues
show
Bug introduced by
The expression $parameters of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
207
            $form .= '<input type="hidden" name="' . $name . '" value="' . $value . '">';
208
        }
209
        $form .= '</form>';
210
211
        return $form;
212
    }
213
214
    public function storeMainfileCheck($needMainfileRewrite, $mainfileKeys)
215
    {
216
        $this->needMainfileRewrite = $needMainfileRewrite;
217
218
        if ($needMainfileRewrite) {
219
            $this->mainfileKeys = $mainfileKeys;
220
        }
221
    }
222
223
}
224