Completed
Pull Request — master (#53)
by
unknown
02:28
created

Package::extractIfMissing()   C

Complexity

Conditions 8
Paths 16

Size

Total Lines 35
Code Lines 23

Duplication

Lines 10
Ratio 28.57 %

Code Coverage

Tests 19
CRAP Score 8.8847

Importance

Changes 7
Bugs 1 Features 0
Metric Value
cc 8
eloc 23
c 7
b 1
f 0
nc 16
nop 2
dl 10
loc 35
ccs 19
cts 25
cp 0.76
crap 8.8847
rs 5.3846
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 array $arch List of supported architectures, or 'noarch'
19
 * @property array $thumbnail List of thumbnail files
20
 * @property array $thumbnail_url List of thumbnail URLs
21
 * @property array $snapshot List of screenshot files
22
 * @property array $snapshot_url List of screenshot URLs
23
 * @property bool $beta TRUE if this is a beta package.
24
 * @property string $firmware Minimum firmware needed on device.
25
 * @property string $install_dep_services Dependencies required by this package.
26
 * @property bool $silent_install Allow silent install
27
 * @property bool $silent_uninstall Allow silent uninstall
28
 * @property bool $silent_upgrade Allow silent upgrade
29
 * @property bool $qinst Allow silent install
30
 * @property bool $qupgrade Allow silent upgrade
31
 * @property bool $qstart Allow automatic start after install
32
 */
33
class Package
34
{
35
    private $config;
36
    private $filepath;
37
    private $filepathNoExt;
38
    private $filename;
39
    private $filenameNoExt;
40
    private $metafile;
41
    private $wizfile;
42
    private $nowizfile;
43
    private $metadata;
44
45
    /**
46
     * @param \SSpkS\Config $config Config object
47
     * @param string $filename Filename of SPK file
48
     */
49 17
    public function __construct(\SSpkS\Config $config, $filename)
50
    {
51 17
        $this->config = $config;
52 17
        if (!preg_match('/\.spk$/', $filename)) {
53 1
            throw new \Exception('File ' . $filename . ' doesn\'t have .spk extension!');
54
        }
55 16
        if (!file_exists($filename)) {
56 1
            throw new \Exception('File ' . $filename . ' not found!');
57
        }
58 15
        $this->filepath      = $filename;
59 15
        $this->filename      = basename($filename);
60 15
        $this->filenameNoExt = basename($filename, '.spk');
61 15
        $this->filepathNoExt = $this->config->paths['cache'] . $this->filenameNoExt;
62 15
        $this->metafile      = $this->filepathNoExt . '.nfo';
63 15
        $this->wizfile       = $this->filepathNoExt . '.wiz';
64 15
        $this->nowizfile     = $this->filepathNoExt . '.nowiz';
65 15
    }
66
67
    /**
68
     * Getter magic method.
69
     *
70
     * @param string $name Name of requested value.
71
     * @return mixed Requested value.
72
     */
73 10
    public function __get($name)
74
    {
75 10
        $this->collectMetadata();
76 10
        return $this->metadata[$name];
77
    }
78
79
    /**
80
     * Setter magic method.
81
     *
82
     * @param string $name Name of variable to set.
83
     * @param mixed $value Value to set.
84
     */
85 5
    public function __set($name, $value)
86
    {
87 5
        $this->collectMetadata();
88 5
        $this->metadata[$name] = $value;
89 5
    }
90
91
    /**
92
     * Isset feature magic method.
93
     *
94
     * @param string $name Name of requested value.
95
     * @return bool TRUE if value exists, FALSE otherwise.
96
     */
97 6
    public function __isset($name)
98
    {
99 6
        $this->collectMetadata();
100 6
        return isset($this->metadata[$name]);
101
    }
102
103
    /**
104
     * Unset feature magic method.
105
     *
106
     * @param string $name Name of value to unset.
107
     */
108 1
    public function __unset($name)
109
    {
110 1
        $this->collectMetadata();
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 8
    public function parseBool($value)
122
    {
123 8
        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 12
    private function fixBoolIfExist($prop)
133
    {
134 12
        if (isset($this->metadata[$prop])) {
135 8
            $this->metadata[$prop] = $this->parseBool($this->metadata[$prop]);
136 8
        }
137 12
    }
138
139
    /**
140
     * Gathers metadata from package. Extracts INFO file if neccessary.
141
     */
142 12
    private function collectMetadata()
143
    {
144 12
        if (!is_null($this->metadata)) {
145
            // metadata already collected
146 12
            return;
147
        }
148 12
        $this->extractIfMissing('INFO', $this->metafile);
149 12
        $this->metadata = parse_ini_file($this->metafile);
150 12
        if (!isset($this->metadata['displayname'])) {
151 12
            $this->metadata['displayname'] = $this->metadata['package'];
152 12
        }
153 12
        $this->metadata['spk'] = $this->filepath;
154
155
        // Convert architecture(s) to array, as multiple architectures can be specified
156 12
        $this->metadata['arch'] = explode(' ', $this->metadata['arch']);
157
158 12
        $this->fixBoolIfExist('silent_install');
159 12
        $this->fixBoolIfExist('silent_uninstall');
160 12
        $this->fixBoolIfExist('silent_upgrade');
161
162 12
        if (isset($this->metadata['beta']) && in_array($this->metadata['beta'], array('true', '1', 'beta'))) {
163 4
            $this->metadata['beta'] = true;
164 4
        } else {
165 12
            $this->metadata['beta'] = false;
166
        }
167
168 12
        $qValue = $this->hasWizardDir()? false : true;
169 12
        $this->metadata['thumbnail'] = $this->getThumbnails();
170 12
        $this->metadata['snapshot']  = $this->getSnapshots();
171 12
        $this->metadata['qinst']     = !empty($this->metadata['qinst'])? parseBool($this->metadata['qinst']):$qValue;
172 12
        $this->metadata['qupgrade']  = !empty($this->metadata['qupgrade'])? parseBool($this->metadata['qupgrade']):$qValue;
173 12
        $this->metadata['qstart']    = !empty($this->metadata['qstart'])? parseBool($this->metadata['qstart']):$qValue;
174 12
    }
175
176
    /**
177
     * Returns metadata for this package.
178
     *
179
     * @return array Metadata.
180
     */
181 3
    public function getMetadata()
182
    {
183 3
        $this->collectMetadata();
184 3
        return $this->metadata;
185
    }
186
      
187
    /**
188
     * Extracts $inPkgName from package to $targetFile, if it doesn't
189
     * already exist. Needs the phar.so extension and allow_url_fopen.
190
     *
191
     * @param string $inPkgName Filename in package
192
     * @param string $targetFile Path to destination
193
     * @throws \Exception if the file couldn't get extracted.
194
     * @return bool TRUE if successful or no action needed.
195
     */
196 13
    public function extractIfMissing($inPkgName, $targetFile)
197
    {
198 13
        if (file_exists($targetFile)) {
199
            // Everything in working order
200 8
            return true;
201
        }
202
        // Try to extract file
203 13
        $tmp_dir = sys_get_temp_dir();
204 13
        $free_tmp = @disk_free_space($tmp_dir);
205 13 View Code Duplication
        if (!empty($free_tmp)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206 13
            if ($free_tmp < 2048) {
207
                throw new \Exception('TMP folder only has ' . $free_tmp . ' Bytes space available. Disk full!');
208
            }
209 13
        }
210 13
        $free = @disk_free_space(dirname($targetFile));        
211 13 View Code Duplication
        if (!empty($free)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
212 13
            if ($free < 2048) {
213
                throw new \Exception('Package folder only has ' . $free . ' Bytes space available. Disk full!');
214
            }
215 13
        }
216
        try {
217 13
            $p = new \PharData($this->filepath, \Phar::CURRENT_AS_FILEINFO | \Phar::KEY_AS_FILENAME);
218 13
        } catch (\UnexpectedValueException $e) {
219
            rename($this->filepath, $this->filepath . '.invalid');
220
            throw new \Exception('Package ' . $this->filepath . ' not readable! Will be ignored in the future. Please try again!');
221
        }
222 13
        $tmpExtractedFilepath = $tmp_dir . DIRECTORY_SEPARATOR . $inPkgName;
223 13
        if (file_exists($tmpExtractedFilepath)) {
224
            // stale file from before - unlink first
225
            unlink($tmpExtractedFilepath);
226
        }
227 13
        $p->extractTo($tmp_dir, $inPkgName);
228 13
        rename($tmpExtractedFilepath, $targetFile);
229 13
        return true;
230
    }
231
232
    /**
233
     * Returns a true if the package contains WIZARD_UIFILES.
234
     *
235
     * @return bool Package has a wizard
236
     */
237 12
    public function hasWizardDir()
238
    {
239 12
        if (file_exists($this->wizfile)) {
240
            return true;
241
        }
242
243 12
        if (file_exists($this->nowizfile)) {
244 3
            return false;
245
        }
246
247
        try {
248 9
            $p = new \PharData($this->filepath, \Phar::CURRENT_AS_FILEINFO | \Phar::KEY_AS_FILENAME);
249 9
        } catch (\UnexpectedValueException $e) {
250
            rename($this->filepath, $this->filepath . '.invalid');
251
            throw new \Exception('Package ' . $this->filepath . ' not readable! Will be ignored in the future. Please try again!');
252
        }
253 9
        foreach ($p as $file) {
254 9
            if (substr($file, strrpos($file, '/') + 1) == 'WIZARD_UIFILES') {
255
                touch($this->wizfile);
256
                return true;
257
            }
258 9
        }
259 9
        touch($this->nowizfile);
260 9
        return false;
261
    }
262
263
    /**
264
     * Returns a list of thumbnails for the specified package.
265
     *
266
     * @param string $pathPrefix Prefix to put before file path
267
     * @return array List of thumbnail urls
268
     */
269 12
    public function getThumbnails($pathPrefix = '')
270
    {
271
        $thumbnailSources = array(
272
            '72' => array(
273 12
                'file' => 'PACKAGE_ICON.PNG',
274 12
                'info' => 'package_icon',
275 12
            ),
276
            '120' => array(
277 12
                'file' => 'PACKAGE_ICON_256.PNG',
278 12
                'info' => 'package_icon_256',
279 12
            ),
280 12
        );
281 12
        $thumbnails = array();
282 12
        foreach ($thumbnailSources as $size => $sourceList) {
283 12
            $thumbName = $this->filepathNoExt . '_thumb_' . $size . '.png';
284
            // Try to find file in package, otherwise check if defined in INFO
285
            try {
286 12
                $this->extractIfMissing($sourceList['file'], $thumbName);
287 12
            } catch (\Exception $e) {
288
                // Check if icon is in metadata
289 12
                $this->collectMetadata();
290 12
                if (isset($this->metadata[$sourceList['info']])) {
291 9
                    file_put_contents($thumbName, base64_decode($this->metadata[$sourceList['info']]));
292 9
                }
293
            }
294
295
            // Use $size px thumbnail, if available
296 12
            if (file_exists($thumbName)) {
297 12
                $thumbnails[] = $pathPrefix . $thumbName;
298 12
            } else {
299
                // Use theme's default pictures
300 12
                $themeUrl = $this->config->paths['themes'] . $this->config->site['theme'] . '/';
301 12
                $thumbnails[] = $pathPrefix . $themeUrl . 'images/default_package_icon_' . $size . '.png';
302
            }
303 12
        }
304 12
        return $thumbnails;
305
    }
306
307
    /**
308
     * Returns a list of screenshots for the specified package.
309
     *
310
     * @param string $pathPrefix Prefix to put before file path
311
     * @return array List of screenshots
312
     */
313 12
    public function getSnapshots($pathPrefix = '')
314
    {
315
        /* Let's first try to extract screenshots from package (SSpkS feature) */
316 12
        $i = 1;
317 12
        while (true) {
318
            try {
319 12
                $this->extractIfMissing('screen_' . $i . '.png', $this->filepathNoExt . '_screen_' . $i . '.png');
320 7
                $i++;
321 12
            } catch (\Exception $e) {
322 12
                break;
323
            }
324 7
        }
325 12
        $snapshots = array();
326
        // Add screenshots, if available
327 12
        foreach (glob($this->filepathNoExt . '*_screen_*.png') as $snapshot) {
328 7
            $snapshots[] = $pathPrefix . $snapshot;
329 12
        }
330 12
        return $snapshots;
331
    }
332
333
    /**
334
     * Checks compatibility to the given $arch-itecture.
335
     *
336
     * @param string $arch Architecture to check against (or "noarch")
337
     * @return bool TRUE if compatible, otherwise FALSE.
338
     */
339 1
    public function isCompatibleToArch($arch)
340
    {
341
        // Make sure we have metadata available
342 1
        $this->collectMetadata();
343
        // TODO: Check arch family, too?
344 1
        return (in_array($arch, $this->metadata['arch']) || in_array('noarch', $this->metadata['arch']));
345
    }
346
347
    /**
348
     * Checks compatibility to the given firmware $version.
349
     *
350
     * @param string $version Target firmware version.
351
     * @return bool TRUE if compatible, otherwise FALSE.
352
     */
353 1
    public function isCompatibleToFirmware($version)
354
    {
355 1
        $this->collectMetadata();
356 1
        return version_compare($this->metadata['firmware'], $version, '<=');
357
    }
358
359
    /**
360
     * Checks if this package is a beta version or not.
361
     *
362
     * @return bool TRUE if this is a beta version, FALSE otherwise.
363
     */
364 1
    public function isBeta()
365
    {
366 1
        $this->collectMetadata();
367 1
        return (isset($this->metadata['beta']) && $this->metadata['beta'] == true);
368
    }
369
}
370