Passed
Push — scrutinizer-test ( 6f2f69...953bdc )
by Pascal
02:22
created

Package::extractIfMissing()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 30
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 9.4924

Importance

Changes 7
Bugs 1 Features 0
Metric Value
cc 8
eloc 20
c 7
b 1
f 0
nc 6
nop 2
dl 0
loc 30
ccs 15
cts 21
cp 0.7143
crap 9.4924
rs 8.4444
1
<?php
2
3
namespace SSpkS\Package;
4
5
/**
6
 * SPK Package class
7
 *
8
 * @property string $spk Path to SPK file
9
 * @property string $spk_url URL to SPK file
10
 * @property string $displayname Pretty printed name of package (falls back to $package if not present)
11
 * @property string $package Package name
12
 * @property string $version Package version
13
 * @property string $description Package description
14
 * @property string $maintainer Package maintainer
15
 * @property string $maintainer_url URL of maintainer's web page
16
 * @property string $distributor Package distributor
17
 * @property string $distributor_url URL of distributor's web page
18
 * @property string $support_url URL of support web page
19
 * @property array $arch List of supported architectures, or 'noarch'
20
 * @property array $thumbnail List of thumbnail files
21
 * @property array $thumbnail_url List of thumbnail URLs
22
 * @property array $snapshot List of screenshot files
23
 * @property array $snapshot_url List of screenshot URLs
24
 * @property bool $beta TRUE if this is a beta package.
25
 * @property string $firmware Minimum firmware needed on device.
26
 * @property string $install_dep_services Dependencies required by this package.
27
 * @property bool $silent_install Allow silent install
28
 * @property bool $silent_uninstall Allow silent uninstall
29
 * @property bool $silent_upgrade Allow silent upgrade
30
 * @property bool $auto_upgrade_from Allow auto upgrade if version is newer than this field
31
 * @property bool $qinst Allow silent install
32
 * @property bool $qupgrade Allow silent upgrade
33
 * @property bool $qstart Allow automatic start after install
34
 */
35
class Package
36
{
37
    private $config;
38
    private $filepath;
39
    private $filepathNoExt;
40
    private $filename;
41
    private $filenameNoExt;
42
    private $metafile;
43
    private $wizfile;
44
    private $nowizfile;
45
    private $metadata;
46
47
    /**
48
     * @param \SSpkS\Config $config Config object
49
     * @param string $filename Filename of SPK file
50
     */
51 17
    public function __construct(\SSpkS\Config $config, $filename)
52
    {
53 17
        $this->config = $config;
54 17
        if (!preg_match('/\.spk$/', $filename)) {
55 1
            throw new \Exception('File ' . $filename . ' doesn\'t have .spk extension!');
56
        }
57 16
        if (!file_exists($filename)) {
58 1
            throw new \Exception('File ' . $filename . ' not found!');
59
        }
60 15
        $this->filepath      = $filename;
61 15
        $this->filename      = basename($filename);
62 15
        $this->filenameNoExt = basename($filename, '.spk');
63 15
        $this->filepathNoExt = $this->config->paths['cache'] . $this->filenameNoExt;
64 15
        $this->metafile      = $this->filepathNoExt . '.nfo';
65 15
        $this->wizfile       = $this->filepathNoExt . '.wiz';
66 15
        $this->nowizfile     = $this->filepathNoExt . '.nowiz';
67
        // Make sure we have metadata available
68 15
        $this->collectMetadata();        
69 15
    }
70
71
    /**
72
     * Getter magic method.
73
     *
74
     * @param string $name Name of requested value.
75
     * @return mixed Requested value.
76
     */
77 9
    public function __get($name)
78
    {
79 9
        return $this->metadata[$name];
80
    }
81
82
    /**
83
     * Setter magic method.
84
     *
85
     * @param string $name Name of variable to set.
86
     * @param mixed $value Value to set.
87
     */
88 5
    public function __set($name, $value)
89
    {
90 5
        $this->metadata[$name] = $value;
91 5
    }
92
93
    /**
94
     * Isset feature magic method.
95
     *
96
     * @param string $name Name of requested value.
97
     * @return bool TRUE if value exists, FALSE otherwise.
98
     */
99 5
    public function __isset($name)
100
    {
101 5
        return isset($this->metadata[$name]);
102
    }
103
104
    /**
105
     * Unset feature magic method.
106
     *
107
     * @param string $name Name of value to unset.
108
     */
109 1
    public function __unset($name)
110
    {
111 1
        unset($this->metadata[$name]);
112 1
    }
113
114
    /**
115
     * Parses boolean value ('yes', '1', 'true') into
116
     * boolean type.
117
     *
118
     * @param mixed $value Input value
119
     * @return bool Boolean interpretation of $value.
120
     */
121 15
    public function parseBool($value)
122
    {
123 15
        return in_array($value, array('true', 'yes', '1', 1));
124
    }
125
126
    /**
127
     * Checks if given property $prop exists and converts it
128
     * into a boolean value.
129
     *
130
     * @param string $prop Property to convert
131
     */
132 15
    private function fixBoolIfExist($prop)
133
    {
134 15
        if (isset($this->metadata[$prop])) {
135 9
            $this->metadata[$prop] = $this->parseBool($this->metadata[$prop]);
136 9
        }
137 15
    }
138
139
    /**
140
     * Gathers metadata from package. Extracts INFO file if neccessary.
141
     */
142 15
    private function collectMetadata()
143
    {
144 15
        if (!is_null($this->metadata)) {
145
            // metadata already collected
146
            return;
147
        }
148 15
        $this->extractIfMissing('INFO', $this->metafile);
149 15
        $this->metadata = parse_ini_file($this->metafile);
150 15
        if (!isset($this->metadata['displayname'])) {
151 15
            $this->metadata['displayname'] = $this->metadata['package'];
152 15
        }
153 15
        $this->metadata['spk'] = $this->filepath;
154
155
        // Convert architecture(s) to array, as multiple architectures can be specified
156 15
        $this->metadata['arch'] = explode(' ', $this->metadata['arch']);
157
158 15
        $this->fixBoolIfExist('silent_install');
159 15
        $this->fixBoolIfExist('silent_uninstall');
160 15
        $this->fixBoolIfExist('silent_upgrade');
161
162 15
        if ($this->isBeta()) {
163 6
            $this->metadata['beta'] = true;
164 6
        } else {
165 15
            $this->metadata['beta'] = false;
166
        }
167
168 15
        $qValue = $this->hasWizardDir()? false : true;
169 15
        $this->metadata['thumbnail'] = $this->getThumbnails();
170 15
        $this->metadata['snapshot']  = $this->getSnapshots();
171 15
        $this->metadata['qinst']     = !empty($this->metadata['qinst'])? parseBool($this->metadata['qinst']):$qValue;
0 ignored issues
show
Bug introduced by
The function parseBool was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

171
        $this->metadata['qinst']     = !empty($this->metadata['qinst'])? /** @scrutinizer ignore-call */ parseBool($this->metadata['qinst']):$qValue;
Loading history...
172 15
        $this->metadata['qupgrade']  = !empty($this->metadata['qupgrade'])? parseBool($this->metadata['qupgrade']):$qValue;
173 15
        $this->metadata['qstart']    = !empty($this->metadata['qstart'])? parseBool($this->metadata['qstart']):$qValue;
174 15
    }
175
176
    /**
177
     * Returns metadata for this package.
178
     *
179
     * @return array Metadata.
180
     */
181 3
    public function getMetadata()
182
    {
183 3
        return $this->metadata;
184
    }
185
      
186
    /**
187
     * Extracts $inPkgName from package to $targetFile, if it doesn't
188
     * already exist. Needs the phar.so extension and allow_url_fopen.
189
     *
190
     * @param string $inPkgName Filename in package
191
     * @param string $targetFile Path to destination
192
     * @throws \Exception if the file couldn't get extracted.
193
     * @return bool TRUE if successful or no action needed.
194
     */
195 15
    public function extractIfMissing($inPkgName, $targetFile)
196
    {
197 15
        if (file_exists($targetFile)) {
198
            // Everything in working order
199 8
            return true;
200
        }
201
        // Try to extract file
202 15
        $tmp_dir = sys_get_temp_dir();
203 15
        $free_tmp = @disk_free_space($tmp_dir);
204 15
        if (!empty($free_tmp) && $free_tmp < 2048) {
205
            throw new \Exception('TMP folder only has ' . $free_tmp . ' Bytes available. Disk full!');
206
        }
207 15
        $free = @disk_free_space(dirname($targetFile));
208 15
        if (!empty($free) && $free < 2048) {
209
            throw new \Exception('Package folder only has ' . $free . ' Bytes available. Disk full!');
210
        }
211
        try {
212 15
            $p = new \PharData($this->filepath, \Phar::CURRENT_AS_FILEINFO | \Phar::KEY_AS_FILENAME);
213 15
        } catch (\UnexpectedValueException $e) {
214
            rename($this->filepath, $this->filepath . '.invalid');
215
            throw new \Exception('Package ' . $this->filepath . ' not readable! Will be ignored in the future. Please try again!');
216
        }
217 15
        $tmpExtractedFilepath = $tmp_dir . DIRECTORY_SEPARATOR . $inPkgName;
218 15
        if (file_exists($tmpExtractedFilepath)) {
219
            // stale file from before - unlink first
220
            unlink($tmpExtractedFilepath);
221
        }
222 15
        $p->extractTo($tmp_dir, $inPkgName);
223 15
        rename($tmpExtractedFilepath, $targetFile);
224 15
        return true;
225
    }
226
227
    /**
228
     * Returns a true if the package contains WIZARD_UIFILES.
229
     *
230
     * @return bool Package has a wizard
231
     */
232 15
    public function hasWizardDir()
233
    {
234 15
        if (file_exists($this->wizfile)) {
235
            return true;
236
        }
237
238 15
        if (file_exists($this->nowizfile)) {
239 5
            return false;
240
        }
241
242
        try {
243 10
            $p = new \PharData($this->filepath, \Phar::CURRENT_AS_FILEINFO | \Phar::KEY_AS_FILENAME);
244 10
        } catch (\UnexpectedValueException $e) {
245
            rename($this->filepath, $this->filepath . '.invalid');
246
            throw new \Exception('Package ' . $this->filepath . ' not readable! Will be ignored in the future. Please try again!');
247
        }
248 10
        foreach ($p as $file) {
249 10
            if (substr($file, strrpos($file, '/') + 1) == 'WIZARD_UIFILES') {
250
                touch($this->wizfile);
251
                return true;
252
            }
253 10
        }
254 10
        touch($this->nowizfile);
255 10
        return false;
256
    }
257
258
    /**
259
     * Returns a list of thumbnails for the specified package.
260
     *
261
     * @param string $pathPrefix Prefix to put before file path
262
     * @return array List of thumbnail urls
263
     */
264 15
    public function getThumbnails($pathPrefix = '')
265
    {
266
        $thumbnailSources = array(
267
            '72' => array(
268 15
                'file' => 'PACKAGE_ICON.PNG',
269 15
                'info' => 'package_icon',
270 15
            ),
271
            '120' => array(
272 15
                'file' => 'PACKAGE_ICON_256.PNG',
273 15
                'info' => 'package_icon_256',
274 15
            ),
275 15
        );
276 15
        $thumbnails = array();
277 15
        foreach ($thumbnailSources as $size => $sourceList) {
278 15
            $thumbName = $this->filepathNoExt . '_thumb_' . $size . '.png';
279
            // Try to find file in package, otherwise check if defined in INFO
280
            try {
281 15
                $this->extractIfMissing($sourceList['file'], $thumbName);
282 15
            } catch (\Exception $e) {
283
                // Check if icon is in metadata
284 15
                if (isset($this->metadata[$sourceList['info']])) {
285 11
                    file_put_contents($thumbName, base64_decode($this->metadata[$sourceList['info']]));
286 11
                }
287
            }
288
289
            // Use $size px thumbnail, if available
290 15
            if (file_exists($thumbName)) {
291 15
                $thumbnails[] = $pathPrefix . $thumbName;
292 15
            } else {
293
                // Use theme's default pictures
294 15
                $themeUrl = $this->config->paths['themes'] . $this->config->site['theme'] . '/';
295 15
                $thumbnails[] = $pathPrefix . $themeUrl . 'images/default_package_icon_' . $size . '.png';
296
            }
297 15
        }
298 15
        return $thumbnails;
299
    }
300
301
    /**
302
     * Returns a list of screenshots for the specified package.
303
     *
304
     * @param string $pathPrefix Prefix to put before file path
305
     * @return array List of screenshots
306
     */
307 15
    public function getSnapshots($pathPrefix = '')
308
    {
309
        /* Let's first try to extract screenshots from package (SSpkS feature) */
310 15
        $i = 1;
311 15
        while (true) {
312
            try {
313 15
                $this->extractIfMissing('screen_' . $i . '.png', $this->filepathNoExt . '_screen_' . $i . '.png');
314 8
                $i++;
315 15
            } catch (\Exception $e) {
316 15
                break;
317
            }
318 8
        }
319 15
        $snapshots = array();
320
        // Add screenshots, if available
321 15
        foreach (glob($this->filepathNoExt . '*_screen_*.png') as $snapshot) {
322 8
            $snapshots[] = $pathPrefix . $snapshot;
323 15
        }
324 15
        return $snapshots;
325
    }
326
327
    /**
328
     * Checks compatibility to the given $arch-itecture.
329
     *
330
     * @param string $arch Architecture to check against (or "noarch")
331
     * @return bool TRUE if compatible, otherwise FALSE.
332
     */
333 1
    public function isCompatibleToArch($arch)
334
    {
335
        // TODO: Check arch family, too?
336 1
        return (in_array($arch, $this->metadata['arch']) || in_array('noarch', $this->metadata['arch']));
337
    }
338
339
    /**
340
     * Checks compatibility to the given firmware $version.
341
     *
342
     * @param string $version Target firmware version.
343
     * @return bool TRUE if compatible, otherwise FALSE.
344
     */
345 1
    public function isCompatibleToFirmware($version)
346
    {
347 1
        return version_compare($this->metadata['firmware'], $version, '<=');
348
    }
349
350
    /**
351
     * Checks if this package is a beta version or not.
352
     *
353
     * @return bool TRUE if this is a beta version, FALSE otherwise.
354
     */
355 15
    public function isBeta()
356
    {
357 15
        return (isset($this->metadata['beta']) && $this->parseBool($this->metadata['beta']));
358
    }
359
}
360